author: Krasimir Tsonev

Hi there, I'm . Senior front-end engineer with over 13 years of experience. I write, speak and occasionally code stuff. Follow me on Twitter, GitHub, Facebook or LinkedIn

Chrome Extension: run JavaScript in the context of the current page

I'm currently working on a Google Chrome extension and I need to run a JavaScript in the context of the current page. The obvious choice for such a logic is the content script. However it is not so easy, because the content script has an access only to the DOM of the current page. It can't run global functions or use global objects.
I solved the problem by inserting a new script node in the current page. The new script tag contains my custom javascript which is run immediately. There is one problem with my solution - you can't get the result back to the extension. So, if you need to run something, but you don't care about the result feel free to use the following script in your content file
var yourCustomJavaScriptCode = '...';
var script = document.createElement('script');
var code = document.createTextNode('(function() {' + yourCustomJavaScriptCode + '})();');
script.appendChild(code);
(document.body || document.head).appendChild(script);
Update: you may get
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' ...".
That's because Content Security Policy. In my case this happens when I'm operating with https sites. So, it looks like this tricky solution, the one with injecting script tag, doesn't work. Luckily Chrome offers another solution - chrome.tabs.executeScript method.
chrome.tabs.getSelected(null, function(tab){
    chrome.tabs.executeScript(tab.id, {code: "alert('test');"}, function(response) {
        
    });
});
This script should be added inside your background script. There is similar method for inserting CSS - insertCSS. The bad news are that the js code send to executeScript can't access another js code available on your page. You have again access only to the DOM elements. Something like this will not work
chrome.tabs.executeScript(tab.id, {code: "MyGlobalObject.method();"});
However it is still helpful, because this works:
chrome.tabs.executeScript(tab.id, {code: "alert(document.querySelector('body'));"});
If you enjoy this post, share it on Twitter, Facebook or LinkedIn. Or maybe comment below: