Ending a Photoshop script when no layers are selected

I’ve been working with a function I found on stackoverflow here that works as far as I can tell by grouping the layers, dumping layer names into an array then ungrouping them.

function getSelectedLayers(){
    var idGrp = stringIDToTypeID( "groupLayersEvent" );
    var descGrp = new ActionDescriptor();
    var refGrp = new ActionReference();
    refGrp.putEnumerated(charIDToTypeID( "Lyr " ),charIDToTypeID( "Ordn" ),charIDToTypeID( "Trgt" ));
    descGrp.putReference(charIDToTypeID( "null" ), refGrp );
    executeAction( idGrp, descGrp, DialogModes.ALL );
    var resultLayers=new Array();
    for (var ix=0;ix<app.activeDocument.activeLayer.layers.length;ix++){resultLayers.push(app.activeDocument.activeLayer.layers[ix])}
    var id8 = charIDToTypeID( "slct" );
        var desc5 = new ActionDescriptor();
        var id9 = charIDToTypeID( "null" );
        var ref2 = new ActionReference();
        var id10 = charIDToTypeID( "HstS" );
        var id11 = charIDToTypeID( "Ordn" );
        var id12 = charIDToTypeID( "Prvs" );
        ref2.putEnumerated( id10, id11, id12 );
    desc5.putReference( id9, ref2 );
    executeAction( id8, desc5, DialogModes.NO );
    return resultLayers;
var layers = getSelectedLayers();

Unfortunately when no layers are selected and this function is run Photoshop throws the message

The command “Group Layers” is not currently available.

Is there any way to at least return a null value when this happens without the script stalling? That way I could display a message about needing to select layers when it’s null.

OR Is there any way to determine that no layers are selected before the function tries to run the grouping function?

Any help is greatly appreciated!


Something like this should work….

var activelayer = application.document.activeLayer;

   var layers = getSelectedLayers();
   alert("Select a Layer");

Source : Link , Question Author : Joeykangaroo , Answer Author : Andy Stone

Leave a Comment