Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
user5858 Avatar asked Oct 27 '25 16:10

user5858


1 Answers

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);
like image 156
Iván Nokonoko Avatar answered Oct 29 '25 07:10

Iván Nokonoko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!