Chrome onMessage Listener not getting called
google-chrome, google-chrome-extension, javascript
Solution
`chrome.extension.sendMessage` only triggers `onMessage` listeners in the extension's scope, excluding content scripts.
You can notify content scripts using the `chrome.tabs.sendMessage` method, as follows:
function myfunc() {
var x = $('#options option:selected').text();
var message = {sel_text: x};
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tabId = tabs[0].id;
chrome.tabs.sendMessage(tabId, message);
});
}
Problem
I am experimenting with the `chrome.extension` API. manifest.json ``` { "name": "First", "version": "1.0", "manifest_version": 2, "description": "First extension", "background": { "scripts": ["test.js"] }, "page_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "content_scripts": [ { "js": [ "jquery.min.js", "display.js" ], "matches": [ "http://*/*", "https://*/*" ] } ], "permissions" : [ "tabs", "http://*/*", "https://*/" ] } ``` display.js ``` alert("inside display.js"); chrome.extension.onMessage.addListener( function(request, sender, sendResponse){ alert("inside msg"); var time = request.sel_text; alert(time); }); ``` test.js ``` function check(tab_id, data, tab){ if(tab.url.indexOf("google") > -1){ chrome.pageAction.show(tab_id); chrome.tabs.executeScript(null, {"file" : "display.js"}) ; } }; chrome.tabs.onUpdated.addListener(check); ``` popup1.js ``` function myfunc(){ var x = $('#options option:selected').text(); alert(x); chrome.extension.sendMessage({sel_text: x}); } $(document).ready(function(){ $('#options').change(myfunc); }); ``` Now, when my page loads I get`three(3)` popups saying `inside display.js` but `chrome.extension.onMessage.addListener` is never called. So, what am I doing wrong. Can we can access `chrome.extension.*` API from content script.