【问题标题】:Userscript to click button用户脚本单击按钮
【发布时间】:2014-03-25 11:41:15
【问题描述】:

我想使用greasemonkey 点击立即购买按钮。

// ==UserScript==
// @name        script
// @namespace   sc
// @include     *
// @version     1
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==

waitForKeyElements ("#buy-now", triggerMostButtons);

function triggerMostButtons (jNode) {
    triggerMouseEvent (jNode[0], "mouseover");
    triggerMouseEvent (jNode[0], "mousedown");
    triggerMouseEvent (jNode[0], "click");
    triggerMouseEvent (jNode[0], "mouseup");
}

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

按钮的 HTML:

<div class="buy-now"><a data-spm-anchor-id="0.0.0.0" data-widget-cid="widget-14" tabindex="-1" id="buy-now" class="buy-now-btn" href="#">Buy Now</a><a id="add-to-cart" class="add-to-cart-btn" href="#">Add to Cart</a></div>

我尝试过其他代码,例如

var TargetLink          = $("a:contains('Ik neem er een!')")
if (TargetLink.length)
    window.location.assign (TargetLink[0].href);

waitForKeyElements ("a.class:contains('buy-now-btn')", clickOnFollowButton);

function clickOnFollowButton (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

有人能给我解释一下在 waitForKeyElements 中放入什么作为单击按钮的第一个参数吗?

【问题讨论】:

    标签: jquery greasemonkey userscripts


    【解决方案1】:

    我想知道下面的代码是不是你想要的。

    document.querySelector('#buy-now').click()
    

    Demo

    在 DOMContentLoaded 时,the page you mentioned 上似乎还没有加载一些脚本。添加延迟为我解决了问题,即

    // ==UserScript==
    // @name         script
    // @namespace    sc
    // @include      http://www.aliexpress.com/item/Free-shipping-100-Genuine-Original-P1000-Mobile-phone-data-cable-for-Samsung-P1000-P6800-P7500-USB/1477114758.html
    // @version      1
    // @description  http://stackoverflow.com/questions/22633509/userscript-to-click-button/22684724
    // @grant        none
    // ==/UserScript==
    setTimeout(function() {
        document.querySelector('#buy-now').click()
    }, 1000)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 2017-04-04
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多