Chrome Extension Send Message From Background.js to Content Script

Tyler Rafferty picture Tyler Rafferty · Jan 15, 2014 · Viewed 15.8k times · Source

I have read the documentation on how to do Send Message From background javascript file(main.js) to Content Script (content.js) but I cannot get the onMessage to open my alert.

Manifest.json

{
   "name": "Example",
   "version": "1.0.1",
   "manifest_version" : 2,
   "description": "Example Description",
   "background" : {
     "scripts" : ["main.js"]
   },
   "page_action" : {
      "default_icon": {
         "19": "icons/19.png",
         "38": "icons/38.png"
      },
      "default_title" : "Example Title"
   },
   "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["lib/jquery-1.8.3.min.js","scripts/content.js"],
      "run_at": "document_idle",
      "all_frames": false
   }],
   "permissions": [
       "tabs",
       "geolocation"
   ],
   "icons": {
       "16": "icons/16.png",
       "48": "icons/48.png",
       "128": "icons/48.png"
   }

}

Background javascript file (main.js)

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {action: "SendIt"}, function(response) {});  
});

Content javascript file (content.js)

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
   if (msg.action == 'SendIt') {
      alert("Message recieved!");
   }
});

Answer

Tyler Rafferty picture Tyler Rafferty · Jan 18, 2014

Thanks to the insight of @Teepeemm I have included a tab load complettion before sending message to content script.

WAIT FOR TAB TO BE FULLY LOADED

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {          
   if (changeInfo.status == 'complete') {   
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
         chrome.tabs.sendMessage(tabs[0].id, {action: "SendIt"}, function(response) {});  
      });
   }
});