Search code examples
javascriptgoogle-chrome-extensiondom-eventsjavascript-injection

How do you rewrite code of a webpage chrome.extension.executeScript


I am writing a Chrome extension that needs to be able to add code into the web page it is viewing. Right now in my background page I have:

chrome.tabs.onUpdated.addListener(function(tabId, info) {
    if (info.status=="complete") {
        chrome.tabs.executeScript(null, {file: "injectme.js"})
    }
})

and the injected script injectme.js which contains a function that looks like this:

function() {
    if (!document.getElementById('searchforme')) {
        x=document.createElement('script')
        x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
        x.setAttribute('id','searchforme')
        document.appendChild(x)
        alert('it is finished')
    } else {
        alert('so close')
    }
}

My question is how do I call this function the moment it loads so it can insert the script into a web page?


Solution

  • If I understood you :) All you need to do is to warp you current function inside something like:

     (function () {
      // your code
      if (!document.getElementById('searchforme')) {
          x=document.createElement('script')
          x.setAttribute('src','https://sites.google.com/site/searchformechrome/files/theinjectedcode.js')
          x.setAttribute('id','searchforme')
          document.appendChild(x)
          alert('it is finished')
        } else {
         alert('so close')
      }
    }());
    

    so it will be an 'immediate invocation' function.