Here are my two favorite ways ...
// Executing an anonymous script function exec(fn) { var script = document.createElement('script'); script.setAttribute("type", "application/javascript"); script.textContent = '(' + fn + ')();'; document.documentElement.appendChild(script); // run the script document.documentElement.removeChild(script); // clean up } script = function() { //sayHello(); alert('hello'); } exec(script); // Append a script from a file in your extension function appendScript(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 popup, and the above code works with script content as well.
EDIT
Thanks to comments from @renocor, a variant of the first method is proposed here, which allows you to send arguments to the function you enter ....
function exec(fn) { var args = ''; if (arguments.length > 1) { for (var i = 1, end = arguments.length - 2; i <= end; i++) { args += typeof arguments[i]=='function' ? arguments[i] : JSON.stringify(arguments[i]) + ', '; } args += typeof arguments[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);
source share