我正在创建一个 Tampermonkey 用户脚本,它会自动点击 Google 翻译网站上的“星标”按钮并保存我的搜索,以便我以后可以查看它们并排练。
这是我目前所得到的:
// @match https://translate.google.com/#en/de/appetit/
var el = document.getElementById("gt-pb-star");
setTimeout(function(){
el.click();
},4000);
我遇到了 2 个问题。
@match
应该是每个 translate.google.com 搜索,而不仅仅是 appetit。如何指定整个域?- 我尝试使用 click() 方法单击“星号”按钮,但它不起作用。不知道为什么。
你能帮我完成这个用户脚本吗?
编辑:似乎将 match
设置为 https://translate.google.com/
可以处理第一个问题。仍然不知道为什么 click() 不起作用。
最佳答案
参见 Choosing and activating the right controls on an AJAX-driven site .
控件并不总是通过点击
来操作。对于 Google 页面尤其如此。
这个按钮有几件事你需要注意:
- 它不会在点击时触发。
- 事件附加到
#gt-pb-star > .trans-pb-button
,不是#gt-pb-star
. - 即使按钮在页面上,它仍然没有准备好。该按钮可能需要数百毫秒才能被点击。
- 在这种情况下,该按钮在启动时是不可见的,并且在它准备好点击的同时变为可见。因此,您必须等到节点既存在又可见。
这是一个 Greasemonkey/Tampermonkey 脚本,可以完成所有这些工作:
// ==UserScript==
// @name _Auto click the Star button on Google Translate
// @match https://translate.google.com/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("#gt-pb-star > .trans-pb-button", clickNodeWhenVisible);
function clickNodeWhenVisible (jNode) {
if (jNode.is (":visible") ) {
triggerMouseEvent (jNode[0], "mouseover");
triggerMouseEvent (jNode[0], "mousedown");
triggerMouseEvent (jNode[0], "mouseup");
}
else {
return true;
}
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
关于javascript - 点击这个谷歌翻译按钮不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876999/