selectObjectsOnActiveArtboard method specific problem

AiScripts
2 min readMay 2, 2023

The selectObjectsOnActiveArtboard method in Adobe Illustrator selects objects on the active artboard that are at least partially within its area. This automatically clears the current selection of objects. But what if you add your own clearing of the app.selection array to the code before calling the method?

Let’s take the example of a script that selects objects on the active artboard and moves them to a new layer. If you selected objects in the document before running the script, selectObjectsOnActiveArtboard forcibly ungroups everything, including clipping masks.

var doc = app.activeDocument;
var lay = doc.layers.add();
lay.name = doc.artboards[0].name;
app.selection = [];
doc.selectObjectsOnActiveArtboard();
alert("Selected objects: " + selection.length);
for (var i = 0; i < app.selection.length; i++) {
app.selection[i].move(lay, ElementPlacement.PLACEATEND);
}
With app.selection=[] you get four separate rectangles instead two groups

Solution

Adobe Illustrator does not always reset the app.selection array correctly. In such situations, you must add a forced redraw of the application windows using the app.redraw() method.

var doc = app.activeDocument;
var lay = doc.layers.add();
lay.name = doc.artboards[0].name;
app.selection = [];
app.redraw(); // Force Illustrator to redraw its window(s)
doc.selectObjectsOnActiveArtboard();
for (var i = 0; i < app.selection.length; i++) {
app.selection[i].move(lay, ElementPlacement.PLACEATEND);
}

If the script is used in Illustrator CS6 and above, an alternative solution is to reset the Select → Deselect menu command: app.executeMenuCommand("deselectall") .

var doc = app.activeDocument;
var lay = doc.layers.add();
lay.name = doc.artboards[0].name;
app.executeMenuCommand("deselectall");
doc.selectObjectsOnActiveArtboard();
for (var i = 0; i < selection.length; i++) {
selection[i].move(lay, ElementPlacement.PLACEATEND);
}

--

--

AiScripts

Sergey Osokin. Product Illustrator, Icon Designer, Script Developer (Ai, Ps). Writing about bugs and tricks in Adobe Illustrator scripts