我正在创建一个 Tampermonkey 用户脚本,它会自动单击 Google 翻译网站上的“星号”按钮并保存我的搜索,以便我以后可以查看它们并进行排练。
This is the button that I am targeting:
这是我到目前为止所得到的:
// @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 搜索而不仅仅是胃口。如何指定整个域?
- 我尝试使用 click() 方法单击“星号”按钮,但它不起作用。不知道为什么。
你能帮我完成这个用户脚本吗?
编辑:似乎设置match
to https://translate.google.com/
处理第一个问题。仍然不知道为什么 click() 不起作用。
See 在 AJAX 驱动的站点上选择并激活正确的控件.
控件并不总是与click
。对于 Google 页面尤其如此。
此按钮有几件事您需要注意:
- 单击时不会触发。
- 事件附于
#gt-pb-star > .trans-pb-button
, not #gt-pb-star
.
- 即使按钮位于页面上,它仍然没有准备好。该按钮可能需要数百毫秒才能单击。
- 在这种情况下,按钮在启动时是不可见的,并且在准备单击的同时变得可见。因此,您必须等到节点同时存在并且visible.
这是一个 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)