活动应用程序中文件的 Applescript 路径

问题描述 投票:0回答:1

我正在尝试运行 applescript 以获取活动应用程序中文件的路径(例如,我正在使用预览查看的 PDF 文档)。

我尝试了这个,它按预期显示了文档的路径:

tell application "Preview"
    set mypath to path of front document
end tell
display dialog(mypath)

问题是当我尝试使用变量名访问活动应用程序时。以下正确显示“预览”(不带引号):

tell application "System Events" 
    set activeApp to name of first application process whose frontmost is true
end tell
display dialog(activeApp)

但是,当我尝试组合这两个块时,我根本无法让它工作,即使在预览中也是如此。

tell application "System Events" 
    set activeApp to name of first application process whose frontmost is true
end tell

tell application activeApp
    set mypath to path of front document
end tell

display dialog(mypath)

对话框中不显示任何内容。

我知道不同的应用程序有不同的方式来指定“当前文档”是什么,但是为什么这不能在单个应用程序上工作超出了我的范围。我对 Applescripts 也很陌生,所以也许有更多经验的人可以看到这个错误?

applescript
1个回答
0
投票

这里的问题是 AppleScripts 在编译时对应用程序引用进行硬编码,因此我们无法在该上下文中使用变量。我们可以通过使用处理程序来解决此限制,如下所示:

tell application "System Events"
    set activeApp to name of first application process whose frontmost is true
    set activeFilePath to my getAppFilePath(activeApp)
    display dialog activeFilePath
end tell

on getAppFilePath(appName)
    tell application appName
        set mypath to path of front document
    end tell
    return mypath
end getAppFilePath

它起作用的原因(我认为)是处理程序在编译时的处理方式与脚本主体的处理方式不同。我确信它会带来性能成本,因为 AppleScript 需要动态创建应用程序引用,但我怀疑这有什么值得注意的。

© www.soinside.com 2019 - 2024. All rights reserved.