Search code examples
javascriptgoogle-chrome-extension

Simulating a click on a page from my chrome extention


I have a chrome extension that finds the pageX and pageY of the window, Is there is a way to fire off a click event of a targeted element, say on google if I wanted to click on the search bar once If found the correct pageX and pageY.

I want to be able to click buttons etc. from the values calculated from my extension but I cant seem to get it to work from content-scripts.js so it there a way to send the pageX and pageY to the background.js scripts.

Something like this:

chrome.action.onClicked.addListener(function (tab) {
       chrome.tabs.executeScript(tab.id,{
           code: 'document.activeElement.click()'
       });
    });

Solution

  • You can simulate click events in JavaScript using the .click() method of the target DOM element.

    It's generally easier/more meaningful to interact with a page using document.querySelector() than it is to use X, Y coordinates, but you can do so using document.elementFromPoint().

    function clickElementAtCoordinate(x, y) {
      const el = document.elementFromPoint(x, y);
      el.click();
    }
    ``