使用JavaScript for Automation在Finder中取消选择all

时间:2016-12-03 19:36:13

标签: macos applescript jxa

使用JavaScript for Automation,我发现自己无法在AppleScript中做一些非常简单的事情。 (震惊,我知道。)

AppleScript:

tell application "Finder" to set selection to {}

清除Finder中的选择。

我无法弄清楚如何在JXA中做同样的事情。

这是我尝试过的:

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

有什么建议吗?

(macOS Sierra,脚本编辑器2.9)

1 个答案:

答案 0 :(得分:0)

[edit] 以下是您可能会考虑更好的另一种“解决方法”。 这通过JXA通过do shell调用osascript发送脚本的AppleScript版本(当然这个技巧是为了获得转义字符):

var app = Application.currentApplication();
app.includeStandardAdditions = true;

app.doShellScript('osascript -e "tell application \\"Finder\\" to set selection to {}"');

------------原创答案-------------

好的,我很确定我应该为这个答案道歉,但是,它确实有效,通过一种奇怪的解决办法,因为在玩了几个小时之后我无法得到更优雅的解决方案。谁知道,也许你会发现这优雅。我几乎。或者也许有人会用一个更好的一个。另外,我只是在脚本编辑器中弄乱了这个。 [编辑]哦,而且,我还在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);