Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...