Skip to content Skip to sidebar Skip to footer

How Can I Make A Chrome Extension Automatically Click A Button When A Page Loads?

I'm trying to create a Google Chrome extension that presses a button on page load. I've been able to trigger the button using VBscript for Internet Explorer by using this code: IE.

Solution 1:

The traditional way to do this is to inject the code:

var scriptNode          = document.createElement ('script');
scriptNode.textContent  = 'changeIframe ();';

document.body.appendChild (scriptNode);


You won't normally have to listen for onload either, as content scripts will fire roughly at that point by default.



The extension JS operates in an "Isolated World" and cannot interact with the page's javascript without some tricks that are not needed here.


Solution 2:

Great that you got a solution, but thought Id show you another way of simulating a click.
With this way you dont have to inject code or know the function that the onclick will run, just get the button and simulate a click....

// https://developer.mozilla.org/en/DOM/element.dispatchEvent
function simulateClick(obj) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var canceled = !obj.dispatchEvent(evt);      
/*

  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
  */
}

var what = document.querySelector('input[type="button"][value="Start!"]');
simulateClick(what);

Post a Comment for "How Can I Make A Chrome Extension Automatically Click A Button When A Page Loads?"