Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Macos 激活最前面的Safari并运行Javascript_Macos_Process_Applescript - Fatal编程技术网

Macos 激活最前面的Safari并运行Javascript

Macos 激活最前面的Safari并运行Javascript,macos,process,applescript,Macos,Process,Applescript,我正在尝试在Safari上运行Javascript,它的最前端是true tell (application "Safari" whose frontmost is true) to do JavaScript theScript in current tab of first window 但我得到一个类似这样的错误: execution error: Can’t get application "System Events" whose frontmost of it = true. Ac

我正在尝试在Safari上运行Javascript,它的最前端是true

tell (application "Safari" whose frontmost is true) to do JavaScript theScript in current tab of first window
但我得到一个类似这样的错误:

execution error: Can’t get application "System Events" whose frontmost of it = true. Access not allowed. (-1723)

哪里出错了?

AppleScript通常要求以特定的方式格式化语法。对于脚本,它无法区分标识符,因为您将它们错误地放在同一行上

set theScript to "alert('Hello, World!');"

tell application "Safari"
    set frontmost to true
    activate
    do JavaScript theScript in current tab of first window
end tell
您可以在AppleScript编辑器中通过编译和运行脚本来测试脚本。
事件
回复
结果
应该可以为您提供一些可能存在问题的指示

编辑:处理最前面(或最近)的流程:*


这很有效。但是,如果有许多Safari正在运行(使用不同的进程ID,注意这里的窗口并不是不同的),并且说我在最前面只有一个Safari为true,那么这个脚本将使用其他Safari,而不是最前面为true的Safari。当您最初提出问题时,您应该指出这一点。更改脚本以处理其进程很容易-请参阅编辑。它在您的机器上工作吗?因为它再次在错误的safari中运行脚本:(您正在尝试获取Safari的最新进程或访问的最后一个Safari窗口吗?如果您能解释一下您希望在此处执行的操作,可能会有所帮助。我正在尝试这样做。因为许多Safari都在运行。我将为脚本提供一个Safari pid,这将使其成为最前端的真实值。这在AS中完成,并且它将很好。现在我想访问这个Safari(最前面的是true),并为这个特定的Safari运行Javascript,而不是在其他Safari上。
set theApp to "Safari"
set theScript to "alert('Hello, World!');"

on isOpen(appName)
    tell application "System Events" to (name of processes) contains appName
end isOpen

set isActive to isOpen(theApp)
if isActive then
    tell application "System Events" to tell (process "Safari" whose frontmost is true)
        tell application "Safari"
            activate
            tell application "System Events" to set frontSafari to item 1 of (get name of processes whose frontmost is true)
            if (count windows) is 0 then
                display dialog "There are no " & theApp & " windows open." buttons {"OK"}
            else if frontSafari is "Safari" then
                tell application "Safari" to do JavaScript theScript in current tab of first window
            end if
        end tell
    end tell
else
    display dialog theApp & " is not currently running." buttons {"OK"}
end if