how to have google chrome extension inject javascript file code example
Example 1: chrome extension dynamically add javascript
chrome.runtime.sendMessage({
injectScript : true,
filename:'/scripts/myfile.js'
}, function(response) {
if(response.done) {
}
});
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if(message.injectScript){
chrome.tabs.executeScript(sender.tab.id, {file: message.filename}, function() {
sendResponse({ done: true });
});
return true;
}
});
Example 2: chrome extension dynamically add javascript
function injectScript(file, node,callback) {
var th = document.getElementsByTagName(node)[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', file);
s.onload = function() {
callback();
};
th.appendChild(s);
}
injectScript(chrome.extension.getURL('myscript.js'), 'body',function(){
});