Click doesn't work on this Google Translate button?

后端 未结 2 507
傲寒
傲寒 2021-01-14 05:06

I am creating an Tampermonkey userscript that would automatically click the \"star\" button on Google Translate website and save my searches so that I can later view them an

2条回答
  •  心在旅途
    2021-01-14 05:48

    See Choosing and activating the right controls on an AJAX-driven site.
    Controls don't always operate with a click. This is especially true with Google pages.

    This button has several things you need to be aware of:

    1. It doesn't fire on click.
    2. The events are attached to #gt-pb-star > .trans-pb-button, not #gt-pb-star.
    3. Even when the button is on the page, it is still not ready. It can take hundreds of milliseconds for that button to be clickable.
    4. In this case, the button is invisible to start and goes visible about the same time it is ready to click. So, you must wait until the node is both present and visible.

    Here is a Greasemonkey/Tampermonkey script that does all that:

    // ==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);
    }
    

提交回复
热议问题