Is it possible to obtain an array of selected artLayer
objects in a native way? Not exactly. However, there is an Action Manager approach that allows you to retrieve descriptors of the selected layers, which can then be used to access the desired information. The following code snippet demonstrates how to extract an array containing names, indexes, and IDs of selected layers, with the ability to retrieve additional data by utilizing different getters on the layer descriptor (desc
). Moreover, a function is included to select artLayers
based on their IDs for obtaining the associated DOM objects. It's worth noting that this method works seamlessly with groups and artboards as well.
var layers = getSelectedLayersInfo();
// Select individual artLayers using their IDs
for (var i = 0; i < layers.length; i++) {
selectByID(layers[i].id);
alert(activeDocument.activeLayer.name);
}
// Reset selection afterwards
for (var i = 0; i < layers.length; i++) {
selectByID(layers[i].id, true);
}
function getSelectedLayersInfo()
{
var lyrs = [];
var lyr;
var ref = new ActionReference();
var desc;
var tempIndex = 0;
var ref2;
ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("targetLayers"));
ref.putEnumerated(charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
var targetLayers = executeActionGet(ref).getList(stringIDToTypeID("targetLayers"));
for (var i = 0; i < targetLayers.count; i++)
{
ref2 = new ActionReference();
// Adjust index depending on existence of background layer
try
{
activeDocument.backgroundLayer;
ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex());
desc = executeActionGet(ref2);
tempIndex = desc.getInteger(stringIDToTypeID("itemIndex")) - 1;
}
catch (o)
{
ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex() + 1);
desc = executeActionGet(ref2);
tempIndex = desc.getInteger(stringIDToTypeID("itemIndex"));
}
lyr = {};
lyr.index = tempIndex;
lyr.id = desc.getInteger(stringIDToTypeID("layerID"));
lyr.name = desc.getString(charIDToTypeID("Nm "));
lyrs.push(lyr);
}
return lyrs;
}
function selectByID(id, add) {
if (add == undefined) add = false;
var desc1 = new ActionDescriptor();
var ref1 = new ActionReference();
ref1.putIdentifier(charIDToTypeID('Lyr '), id);
desc1.putReference(charIDToTypeID('null'), ref1);
if (add) desc1.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
executeAction(charIDToTypeID('slct'), desc1, DialogModes.NO);
} // end of selectByID()