0

I am not able to pass message from background page to content page, below is my code. I have tried downloading code samples from extension library, but it is not working even after that,

background.js:

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.sendMessage(tab.id, {
        greeting: "hello"
    }, function (response) {
        alert(JSON.stringify(response, null, 4));
    });
});

content.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    sendResponse({farewell: "goodbye"});
});

manifest.json:

{
    "name": "Test Screenshot Extension",
    "version": "1.3",
    "description": "Demonstrate screenshot functionality in the chrome.tabs api.",
    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },
    "icons": {
        "128": "icon-128.png",
        "48": "icon-48.png"
    },
    "browser_action": {
        "default_icon": "icon-128.png",
        "default_title": "Take a screen shot!"
    },
    "permissions": ["tabs"],
    "manifest_version": 2
}

The line alert(JSON.stringify(response, null, 4)); alerts"undefined"

6
  • 2
    Where are you injecting the content script?
    – BeardFist
    Sep 7, 2015 at 15:57
  • If you check sample extension named Email this page (by Google), they aren't also injecting the content.js via manifest json. Sep 7, 2015 at 16:02
  • They use chrome.tabs.executeScript to inject it but you don't?
    – wOxxOm
    Sep 7, 2015 at 16:03
  • So what need to be done to make my code work? Through manifest or by using execute script? Sep 7, 2015 at 16:05
  • 1
    Yes, either via manifest so that it's injected always on the specified urls or via executeScript so that it's injected for example after you click the button in which case you might not need messaging depending on what you actually do in the content script.
    – wOxxOm
    Sep 7, 2015 at 16:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.