Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get message from background script

I have a problem, when getting message from background script. My mind almost blowed, where is mistake?

manifest

{
    "name":"Some name",
    "version":"0.1",
    "manifest_version": 2,
    "description":"extension for Google Chrome",
    "permissions": ["tabs","http://*/*", "https://*/*", "<all_urls>","notifications","contextMenus","alarms","tabs","bookmarks"],
    "content_scripts":[
    {
        "matches":["<all_urls>"],
        "css":["style.css"],
        "js":["content.js","jquery.js"]
    }
    ],
    "background": {
        "scripts": ["background.js","jquery.js"],
        "persistent": false
    },
    "icons":{
        "16": "images/icon16.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "browser_action": {
        "default_icon": {
            "19": "images/icon19.png",           
            "38": "images/icon38.png"
        },
        "default_title": "Order Checker",
        "default_popup": "popup.html"
    }
} 

background.js

chrome.tabs.getSelected(null, function(tab) {
    console.log('Loaded!');
    chrome.tabs.sendMessage(tab.id, {
        greeting: "hello"
    });
    console.log('Sended on '+tab.id+'...');
});

content.js

chrome.extension.onMessage.addListener(function(msg, _, request) {
    console.log('Getting request...');
    console.log(msg.greeting);
});

In background page I'm getting in console 2 messages, as expected. But on content page I don't have any messages, so I think it's problem with code in content.js. What I'm doing wrong?

like image 568
lesha_89 Avatar asked Mar 07 '26 09:03

lesha_89


1 Answers

chrome.tabs.getSelected() is deprecated from Chrome 16, use chrome.tabs.query() instead.

Problem in Your Script

chrome.tabs.getSelected() returns reference of current selected tab, which after load of extension is chrome://chrome/extensions/ so your background page is sending message to extensions page where content scripts do not execute

Modify your background script to suit chrome.tabs.query(), you can see messages in console of web pages!

References

  • tabs.query
like image 173
Sudarshan Avatar answered Mar 10 '26 07:03

Sudarshan