Skip to content Skip to sidebar Skip to footer

Chrome-extension: Invoke Page Script By Injection

Is it possible to inject a javascript file into the DOM and immediately execute it ? I wish to invoke javascript functions within the page/DOM. A single content script will not wor

Solution 1:

Here's my two favorite ways...

// Executing an anonymous scriptfunctionexec(fn) {
   var script = document.createElement('script');
   script.setAttribute("type", "application/javascript");
   script.textContent = '(' + fn + ')();';
   document.documentElement.appendChild(script); // run the scriptdocument.documentElement.removeChild(script); // clean up
}

script = function() {
//sayHello();alert('hello');
}

exec(script);

// Append a script from a file in your extensionfunctionappendScript(scriptFile) {
   var script = document.createElement('script');
   script.setAttribute("type", "application/javascript");
   script.setAttribute("src", chrome.extension.getURL(scriptFile));
   document.documentElement.appendChild(script); // run the script
}

appendScript('someFile.js');

Also chrome.tabs.executeScript() can be used from a browser/page action popup and the above code works in a content script aswell.

EDIT Thanks to comments by @renocor, here's a variation of the first method that allows you to send arguments to the injected function....

functionexec(fn) {
    var args = '';
    if (arguments.length > 1) {
        for (var i = 1, end = arguments.length - 2; i <= end; i++) {
            args += typeofarguments[i]=='function' ? arguments[i] : JSON.stringify(arguments[i]) + ', ';
        }
        args += typeofarguments[i]=='function' ? arguments[arguments.length - 1] : JSON.stringify(arguments[arguments.length - 1]);
    }
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')(' + args + ');';
    document.documentElement.appendChild(script); // run the scriptdocument.documentElement.removeChild(script); // clean up
}

script = function(what, huh, nah, yeah) {
    console.debug(arguments);
    console.debug('what=', what);
    console.debug('huh=', huh);
    console.debug('nah=', nah);
    console.debug('yeah=', yeah);
    if (typeof yeah=='function') yeah();
}

exec(script, 'meh', ['bleh'], {
    a: {
        b: 0
    }
}, function(){
    alert('hi');
});

console.debug('No arguments');

exec(script);

Post a Comment for "Chrome-extension: Invoke Page Script By Injection"