user3334776
user3334776

Reputation: 113

Chrome extension: sendMessage doesn't work

I've already read the documentation from Google on 'message passing' a few times and have probably looked at over 10 other questions with the same problem and already tried quiet a few variations of most of their "solutions" and of what I have below... This is black magic, right? Either way, here it goes.

Manifest File:

{
    "manifest_version" : 2,
    "name" : "Message Test",
    "version" : "1.0",

    "browser_action": { 
        "default_popup": "popup.html"
    },

    "background": {
        "scripts": ["background.js"]
    },

    "content_scripts": [
        {
        "matches" : ["<all_urls>"],
        "js": ["message-test.js"]
        }
    ]    
}

I'm aware extensions aren't suppose to use inline JS, but I'm leaving this in so the original question can be left as it was since I still can't get the message to send from the background page, When I switch from the popup to the background, I removed the appropriate lines from the manifest.json

popup.html file:

<html>
  <head>
    <script>
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
        console.log(response.farewell);
      });
    });
    </script>
  </head>
<body>
</body>
</html>

OR

background.js file:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
    console.log(response.farewell);
  });
});

message-test.js file:

var Mymessage;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.greeting == "hello"){
        Mymessage = message.theMessage;
        alert(Mymessage);
    }
    else{
        sendResponse({});
    }
});

I get an undefined alert...

I'm also trying to execute this after pressing a button from a popup and having a window at a specified url, but that's a later issue. The other files for the button and window can be found here except with the background.js content wrapped in an addEventListener("click"....: http://pastebin.com/KhqxLx5y AND http://pastebin.com/JaGcp6tj

Upvotes: 4

Views: 6209

Answers (3)

Xan
Xan

Reputation: 77551

Careful reading of this answer may help you. Every point there applies to your problem.

Your problem is in when your main script is executing, and when your content scripts are. You need to ensure there is a content script listening before you send a message to it, in worst case injecting it programmatically.

And to get it working in a popup, follow KAdot's answer.

Upvotes: 2

dIsoVi
dIsoVi

Reputation: 869

Here is the solution, using background script:

manifest.json

{
    "manifest_version" : 2,
    "name" : "Message Test",
    "version" : "1.0",

    "background":{
        "scripts":["popup.js"]
    },

    "content_scripts": [
        {
        "matches" : ["<all_urls>"],
        "js": ["message-test.js"]
        }
    ]
}

message-test.js

var port = chrome.runtime.connect();
port.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.greeting == "Can you hear me?"){
        alert("Test");
    }
    else{
        sendResponse({});
    }
});

popup.js

chrome.runtime.onConnect.addListener( function ( port ) {
port.postMessage({
        greeting: "Can you hear me?"
    });
});

Some explanaition: first we are connecting to our background script from content script and then background script sends message to content script.

Update

I've improved answer according to @Xan remark. But the idea is the same, first of all you should let know your background script of the existence of content script.

Upvotes: -1

KAdot
KAdot

Reputation: 2087

There are several issues in your code.

Chrome doesn't allow inline scripts in extensions. You must divide your popup.html to script + HTML:

// popup.html
<html>
<body>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

// popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];  // do not forget to declare "tab" variable
    chrome.tabs.sendMessage(tab.id, {
        greeting: "Can you hear me?"
    }, function(response){});
});

Upvotes: 3

Related Questions