macos 为什么当在浏览器中输入相同的代码时,Applescript 中的“do javascript”调用不执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6561452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why doesn't 'do javascript' call in Applescript execute when the same code typed into browser does?
提问by mix
I'm trying to figure out why my Applescript does nothing when the same javascript code typed into a Safari location bar works.
我试图弄清楚为什么我的 Applescript 在输入到 Safari 位置栏中的相同 javascript 代码有效时什么也不做。
Go to a search results page, such as: http://www.google.com/search?q=test. For the correct behavior, type this into the location bar and hit enter:
转到搜索结果页面,例如:http://www.google.com/search?q=test。对于正确的行为,在地址栏中输入以下内容并按回车键:
javascript: document.getElementsByClassName('vspib')[0].click();
You'll see that it selects the magnifier for the first search result.
您会看到它为第一个搜索结果选择了放大镜。
This is what I want to make happen via javascript. So I typed up the following:
这就是我想通过 javascript 实现的。所以我输入了以下内容:
tell application "Safari"
activate
do JavaScript "document.getElementsByClassName('vspib')[0].click();" in document 1
end tell
However, it does nothing. Any ideas?
然而,它什么也不做。有任何想法吗?
回答by sakra
The problem is that do JavaScript
has to correctly address a tab in a Safari window.
问题是do JavaScript
必须正确处理 Safari 窗口中的选项卡。
The following script works for me, if the search results page is the current tab in the frontmost Safari window:
如果搜索结果页面是最前面的 Safari 窗口中的当前选项卡,则以下脚本适用于我:
tell application "Safari"
activate
set theScript to "document.getElementsByClassName('vspib')[0].click();"
do JavaScript theScript in current tab of first window
end tell