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 getthree(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.
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);
    });
}
                        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