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!"); } });
When sending a message to the content script, we need to specify which tab to send it to. Therefore, we need to retrieve the active tab information first, and then use tabs. sendMessage . To use the tabs API and to have access to the active tab, you need to add tabs and activeTab under permissions in your manifest.
Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel. A message can contain any valid JSON object (null, boolean, number, string, array, or object).
According to the official docs you should use postMessage in the sender and message event listener in the receiver. var data = { type: "FROM_PAGE", text: "Hello from the webpage!" }; window. postMessage(data, "*"); Content script: (injected using chrome.
Chrome has documentation on sending messages from webpages to chrome extensions. You add an “externally_connectable” object to your manifest. This will specify which webpages you want to allow to communicate with your extension (in this case, localhost, since I was developing on my machine).
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) {}); }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With