点击对此Google翻译按钮不起作用?

pot*_*ato 3 javascript greasemonkey userscripts tampermonkey

我正在创建一个Tampermonkey用户脚本,它会自动点击谷歌翻译网站上的"星标"按钮并保存我的搜索,以便我以后可以查看它们并进行排练.

这是我定位的按钮: 在此输入图像描述

这是我到目前为止所得到的:

// @match        https://translate.google.com/#en/de/appetit/
var el = document.getElementById("gt-pb-star");
setTimeout(function(){
el.click();
},4000);
Run Code Online (Sandbox Code Playgroud)

我遇到了2个问题.

  1. @match应该是每个translate.google.com搜索,而不仅仅是胃口.如何指定整个域?
  2. 我尝试使用click()方法单击"星形"按钮,但它不起作用.不知道为什么.

你能帮我完成这个用户吗?

编辑:看来,设置matchhttps://translate.google.com/处理的第一个问题.仍然不知道为什么click()不起作用.

Bro*_*ams 6

请参阅在AJAX驱动的站点上选择并激活正确的控件.
控制并不总是与a一起使用click.Google页面尤其如此.

此按钮有几个您需要注意的事项:

  1. 点击时不会触发.
  2. 这些事件是附属于#gt-pb-star > .trans-pb-button,而不是 #gt-pb-star.
  3. 即使按钮在页面上,它仍然没有准备好.该按钮可以点击几百毫秒.
  4. 在这种情况下,该按钮在启动时是不可见的,并且在准备点击的同时可见.因此,您必须等到节点同时存在且可见.

这是一个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);
}
Run Code Online (Sandbox Code Playgroud)