"why is chrome.tabs.executescript() necessary to change the current website dom and how can i use jquery to achieve the same effect?" Code Answer


the javascript you are running in your chrome extension is run either in the background page or some popup page. it is not the page in your browser where you were when running the extension. that is why you need to executescript inside a specific tab.

to visualize this better, right click on the button of your extension, and select inspect popup. the same for a background page, go to chrome://extensions to your (presumably) unpacked extension and click on background page, and you have developer tools to see what is going on.

in order to package some resources in your chrome extension so they can be used by direct access from web pages later on, you can use web accessible resources. basically you declare the files that you want accessible by the web pages, then you can load them in or inject them using a url of the form "chrome-extension://[package id]/[path]". in order to use this mechanism and make the packaged jquery library available to web pages, we add:

"web_accessible_resources": [

in manifest.json.

in order to have access to web pages from the extension, you need to add permissions for it:

"permissions" : [

also in manifest.json. <all_urls> is a special keyword not something i added there and it is a placeholder for any type of url, regardless of schema. if you want only http and https urls, just use the last two only.

here is a function that loads jquery in the page of a certain tab, assigning it the name ex$ so that it doesn't conflict with other libraries or versions of jquery.

function initjqueryonwebpage(tab, callback) {
    // see if already injected
    chrome.tabs.executescript(tab.id,{ code: '!!window.ex$'},function(installed) {
        // then return
        if (installed[0]) return;
        // load script from extension (the url is chrome.extension.geturl('jquery-2.2.2.min.js') )
        chrome.tabs.executescript(tab.id,{ file: 'jquery-2.2.2.min.js' },function() {
            // make sure we get no conflicts
            // and return true to the callback
            chrome.tabs.executescript(tab.id,{ code: 'window.ex$=jquery.noconflict(true);true'},callback);

this function is loading jquery from the extension to the web page, then executes a callback when it's installed. from then one can use the same chrome.tabs.executescript(tab.id,{ code/file: to run scripts using jquery on the remote page.

since it uses the executescript method with the file option, it doesn't need the web_accessible_resources declaration for the script

from a nice comment below, i learned about execution environment. executescript runs in an "isolated world" so that it doesn't have access to global variables and whatever gets executed doesn't create something that can be accessed by the web page. so the entire complicated function above is overkill. you can still use this system if you do not want to interact with code on the page, but just with its dom, and be unconcerned with any conflicts in code

but the extension does have access to the document of the tab. here is a function that uses the web_accessible_resources mechanism described at first to create a script tag in the web page that then loads the jquery library that is packaged in the extension:

// executescript's a function rather than a string
function remex(tabid, func,callback) {
    chrome.tabs.executescript(tabid,{ code: '('+func.tostring()+')()' },callback);

function initjqueryonwebpage(tab, callback) {
    // the function to be executed on the loaded web page
    function f() {
        // return if jquery is already loaded as ex$
        if (window.ex$) return;
        // create a script element to load jquery
        var script=document.createelement('script');
        // create a second script tag after loading jquery, to avoid conflicts
        script.onload=function() {
            var noc=document.createelement('script');
            // this should display in the web page's console
            noc.innerhtml='window.ex$=jquery.noconflict(true); console.log('jquery is available as ',window.ex$);';
        // use extension.geturl to get at the packed script
    // execute the content of the function f
    remex(tab.id,f,function() { 
       console.log('jquery injected'); // this should log in the background/popup page console
       if (typeof(callback)=='function') callback();

it is cumbersome to send scripts to executescripts, that is why i used the remex function above. note that there is a difference between remex, which executes a function in the 'isolated world' environment and the code executed by the tab when a script tag is appended to the document. in both cases, though, what actually gets executed is strings, so be careful not to try to carry objects or functions across contexts.

two consecutive remex calls will be executed in their own context, so even if you load jquery in one, you won't have it available in the next. one can use the same system as in initjqueryonwebpage, though, meaning adding the code to a script on the page. here is a bit of code, use it just like remex:

function windowcontextremex(tabid,func,callback) {
    var code=json.stringify(func.tostring());
    var code='var script = document.createelement("script");'+
        'script.innerhtml = "('+code.substr(1,code.length-2)+')();";'+
    chrome.tabs.executescript(tabid, {
        code : code
    }, function () {
        if (callback)
            return callback.apply(this, arguments);

so here i have demonstrated:

  • executing code in an isolated context that has only access to the dom of a page opened in a tab
  • executing packaged scripts in the same context as above
  • injecting scripts that run in the context of the page

what is missing:

  • a nice way of chaining code so that you don't have to create the script element manually
  • loading css files through insertcss (akin to executescript with a file option, but that load directly in the page
By velodrome on October 12 2022

Answers related to “why is chrome.tabs.executescript() necessary to change the current website dom and how can i use jquery to achieve the same effect?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.