Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome onMessage Listener not getting called

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.

like image 898
RanRag Avatar asked Dec 30 '12 11:12

RanRag


1 Answers

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);
    });
}
like image 139
Rob W Avatar answered Oct 24 '22 00:10

Rob W