Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

google chrome extension - How to trigger click on a button

I've this page. I need to trigger a click on the BUY NOW button on this page using AngularJS.

I've tried these ways to click on this "BUY NOW" in content script(myscript.js) but does not work:

   angular.element($('ul form button:contains("BUY NOW")').get(0)).triggerHandler('click');

       $('ul form button:contains("BUY NOW")').get(0).click();

        $('ul form button:contains("BUY NOW")').get(0).dispatchEvent(new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': true
        }));

The manifest.json looks like this:

"content_scripts": [
        {
            "run_at": "document_end",
            "all_frames": false,
            "matches": ["*://www.flipkart.com/*"],
            "css": [ "jqueryui/jquery-ui.css", "js/slidenavi/sidenavi-right.css","main.css", "js/bootstrap-switch-master/dist/css/bootstrap3/bootstrap-switch.min.css"],
            "js": ["jquery-2.1.4.min.js", "jqueryui/jquery-ui.min.js","js/angular.min.js", "js/jquery.cookie.js", "jqueryui/jquery-ui.min.js","js/slidenavi/SideNavi.js", "client_server_common.js", "user-selections.js",
                "jquery.countdown.min.js", "js/bootstrap-switch-master/dist/js/bootstrap-switch.min.js", "js/cryptojs/rollups/md5.js",  "common.js",
                "myscript.js"
            ]
        }
    ],

What is the way to make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try with this code; it simulates a mouse left click on the element by a quick succession of mousedown, mouseup and click events fired in the center of the button:

var simulateMouseEvent = function(element, eventName, coordX, coordY) {
  element.dispatchEvent(new MouseEvent(eventName, {
    view: window,
    bubbles: true,
    cancelable: true,
    clientX: coordX,
    clientY: coordY,
    button: 0
  }));
};

var theButton = document.querySelector('ul form button');

var box = theButton.getBoundingClientRect(),
        coordX = box.left + (box.right - box.left) / 2,
        coordY = box.top + (box.bottom - box.top) / 2;

simulateMouseEvent (theButton, "mousedown", coordX, coordY);
simulateMouseEvent (theButton, "mouseup", coordX, coordY);
simulateMouseEvent (theButton, "click", coordX, coordY);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...