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
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.
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.
Sadly the prototype didn’t work with Photoshops EMCA limits, so I turned it into a function:
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:
Personally I have adapted this function to accept an optional document: