chrome extension inject function code example

Example: 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()
  }
});