skip to Main Content

Is there a (better) way to determine if a selection is present in a layer in Photoshop without having using a try/catch on the selection.bounds?

try
{
    var sel = app.activeDocument.selection.bounds;
}
catch(e)
{
    var sel = undefined;
    alert("No selection");
}

if (sel) alert(sel);

If there is no selection instead of the (expected) undefined bounds getting returned, I just get the error 1302: No such element. Hence the need for a try/catch.

3

Answers


  1. I was running into this too, and while I didn’t find a way around using a try..catch, I just added a simple active() function to the Selection prototype that I could test.

    Selection.prototype.active = function()
    {
        try      { return (selection.bounds) ? true : false; }
        catch(e) { return false; }
    }
    

    This way, you can just call app.activeDocument.selection.active() to see if something is selected.

    The ternary operator in the try section is there in case they ever fix Selection.bounds to report undefined in the future.

    Login or Signup to reply.
  2. Sadly the prototype didn’t work with Photoshops EMCA limits, so I turned it into a function:

    var mySelection = is_selection_active();
    alert(mySelection);
    
    function is_selection_active()
    {
      var layerRef = app.activeDocument.selection;
    
      try      { return (layerRef.bounds[0]) ? true : false; }
      catch(e) { return false; }
    }
    
    Login or Signup to reply.
  3. Unfortunately above function is erroneous because it would return false if left x-coordinate of the selection would be 0. This may be corrected by checking only the reference (i.e. remove [0] from bounds) or return true in both test cases of the ternary expression. In general I would tend to the latter solution when it comes to JavaScript, but in this specific case I would prefer the first method by removing the index because this is an undocumented feature testing and this test would also cover future changes in the API which may set bounds to null is no selection is active.

    So the above function becomes:

    function selection_active()
    {
      var layerRef = app.activeDocument.selection;
    
      try      { return (layerRef.bounds) ? true : false; }
      catch(e) { return false; }
    }
    

    Personally I have adapted this function to accept an optional document:

    function selectionActive(doc)
    {
      if(doc==null) doc=app.activeDocument;
    
      try      { return doc.selection.bounds ? true : true; }
      catch(e) { return false; }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search