chrome extention append script in webpage code example

Example 1: chrome extension dynamically add javascript

// content script
chrome.runtime.sendMessage({
    injectScript : true,
  	filename:'/scripts/myfile.js'
  }, function(response) {
  if(response.done) {
  	//handle something when script is done
  }
});

// background script
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; // Required for async sendResponse()
  }
});

Example 2: chrome extension dynamically add javascript

//inject another js file from content script w/ callback
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(){
//mysript.js is done loading
});