Applescript:通过变量来判断困境

Applescript:通过变量来判断困境,applescript,applescript-objc,Applescript,Applescript Objc,我想这样做: tell application "Finder" to set appName to (application file id "com.google.Chrome") as text using terms from application appName tell application appName to get URL of active tab of first window end using terms from 这不起作用,因为“使用来自的术语”需要应

我想这样做:

tell application "Finder" to set appName to (application file id "com.google.Chrome") as text
using terms from application appName
    tell application appName to get URL of active tab of first window
end using terms from
这不起作用,因为“使用来自的术语”需要应用程序名称作为字符串常量。如果我替换这一行:

using terms from application appName
用这个

using terms from application "Google Chrome"
它起作用了。然而,我不想依赖目标机器上名为“GoogleChrome”的应用程序。使用bundle标识符似乎更安全。有更好的方法吗

编辑 按照@regulus6633的建议,我尝试了以下方法:

NSAppleScript* script = [[NSAppleScript alloc] initWithSource:
    @"tell application \"Finder\" to set appName to (application file id \"com.google.Chrome\") as text"
    @"\nusing terms from application \"Google Chrome\""
    @"\ntell application appName to get URL of active tab of first window"
    @"\nend using terms from"];

这很好,但如果我在另一台计算机上运行相同的(编译的)应用程序,其中“谷歌浏览器”重命名为“谷歌浏览器”,我会弹出一个对话框,询问“谷歌浏览器”在哪里。似乎NSAppleScript是在运行时编译的?

您误解了“使用来自”的术语的作用。这是一种使用应用程序在计算机上编译脚本,然后不在用户计算机上重新编译脚本的方法。换句话说,一旦你用那一行代码在你的计算机上编译,那么那一行代码在用户的计算机上什么都不做,因此用户不需要你用来编译脚本的应用程序。。。那条线正是你要找的。确保将脚本保存为“应用程序”,这样就不需要在用户的计算机上重新编译

这就是您实际希望代码的外观:

-- here you determine what the user's browser is
set usersBrowser to "whatever"

using terms from application "Google Chrome"
    tell application usersBrowser
        -- here you do something in the user's browser
        -- you have to make sure that whatever command you use is applicable to both google chrome and whatever browser the user is using i.e. the command must work in both browsers
    end tell
end using terms from

我已经在cocoa应用程序中将其实现为NSApplescript。它将与应用程序包一起编译吗?NSApplescript编译读入其中的代码。因此,如果您想在objective-c程序中使用变量applescript代码,那么最好的办法是在objective-c代码中动态创建applescript。然后使用NSApplescript编译代码,这些代码应该适合每个用户的情况。您可以在行之间使用“\n”创建一个包含applescript代码行的NSString,然后使用NSApplescript的initWithSource:method创建applescript。我尝试过这样做,但在重命名应用程序后,它不起作用。我已经用我所做的更新了我的问题。搜索用于确定用户默认浏览器的代码。在创建applescript代码之前使用它。一旦知道浏览器的名称,就创建NSString。。。但不要使用“使用来自”的术语。没有理由这么做。只需将“告诉应用程序”与您先前确定的默认broser名称一起使用即可。问题是我需要使用多个浏览器,而不仅仅是用户的默认浏览器。我最后做的是编译applescript并将其保存在我的应用程序包中,然后使用NSAppleScript的initWithContentsOfURL方法来执行脚本。我希望把所有的源代码都保存在内部,但我找不到其他方法。