Playing around with JavaScript for Automation, I find myself not able to do something that is very simple in AppleScript. (Shocker, I know.)
This AppleScript:
tell application "Finder" to set selection to {}
clears the selection in Finder.
I just cannot figure out how to do the same in JXA.
Here's what I've tried:
var finder = Application("Finder")
finder.includeStandardAdditions = true
//this selects files in the front window...
finder.select( [...array of file paths...] )
//so you'd think this might work to deselect all...
finder.select( [] )
//...but it doesn't do anything
//then I tried each of these in turn...
finder.select( null )
//Error -10010: Handler can't handle objects of this class.
finder.selection = null
//Error -10010: Handler can't handle objects of this class.
finder.selection = []
//Script Editor crashes
//...but none were successful
Any suggestions?
(macOS Sierra, Script Editor 2.9)
[edit] Here's another "work-around" which you might consider better. This sends the AppleScript version of the script through osascript called by do shell via JXA (the trick is of course to get the escape characters right):
var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.doShellScript('osascript -e "tell application \\"Finder\\" to set selection to {}"');
------------original answer-------------
Ok I'm pretty sure I should apologize for this answer, but, well, it does work, via a weird work-around, because I could not get a more elegant solution after playing with it for a couple hours. Who knows, maybe you'll find this elegant. I almost do. Or maybe someone will chime in with a better one. Also, I've only been messing with this in Script Editor. [edit] Oh, and also, I'm still on 10.10.5
//this allows use of JXA version of do shell script later
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var thefinder = Application("Finder");
//Would advise using if/then here to check if there's at least one window, like:
// if (thefinder.windows.length != 0) {
//gets front window (where selection is, always)
var fWin = thefinder.windows[0];
//gets the "target", which is the folder ref
var fWinTarget = fWin.target();
//gets the url of the target
var winU = fWinTarget.url();
//makes that a path
var winUPath = Path(winU);
//closes the original finder window (ref)
fWin.close();
//opens it up again! no more selection!
app.doShellScript("open " + winU);