Question

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!");
   }
});
Was it helpful?

Solution

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) {});  
      });
   }
});

OTHER TIPS

Sidenote: chrome.extension.onMessage is deprecated, you should be using chrome.runtime.onMessage - although I don't believe this will solve your problem.

I remember that I had an issue injecting a minified jquery file using content scripts. Try to use an un-minified version (ie jquery-1.8.3.js). Once you have done that, also add jquery-1.8.3.js to web_accessible_resources in your manifest file. (Read about that here)

If it still doesn't work, my last suggestion would be to add "<all_urls>" to the permissions array in your manifest.

If you have each script announce its presence (I prefer console.log to alert), you see that the background script runs once (on installation or startup), while the content script runs with each new page. This means that you'll want to have some external event trigger the message. Something like

chrome.pageAction.onClicked.addListener(function(tab) {
    chrome.tabs.sendMessage(tab.id,{action:"SendIt"});
});

And don't forget to call chrome.pageAction.show(tabId); as appropriate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top