B
B
BulatDos2015-08-16 20:48:52
JavaScript
BulatDos, 2015-08-16 20:48:52

Why is messaging not working in Chrome Extension?

Hi everyone, I'm writing a chrome extension. In the extension, I set the settings for the script, in background.js I write the send:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
                    console.log(response.farewell);
                    });
                });

I get an error in popup.html :
Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined
at chrome-extension://pkeodebpncilhjkihpmkpkinjocodfdh/background.js:33:41handler @ extensions::uncaught_exception_handler:8exports.handle @ extensions::uncaught_exception_handler: 100EventImpl.dispatch_ @ extensions::event_bindings:376EventImpl.dispatch @ extensions::event_bindings:393target.(anonymous function) @ extensions::SafeBuiltins:19publicClass.(anonymous function) @ extensions::utils:94dispatchOnDisconnect @ extensions::messaging:302

There is an injection.js file that I embed into a remote site via onLoad (), I write a settings receiver there:
chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
    });

When loading, it starts to swear:
Uncaught TypeError: Cannot read property 'addListener' of undefined

What am I doing wrong?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BulatDos, 2015-08-17
@BulatDos

All figured out, on the injection side:

var editorExtensionId = "dkjkabjbiklebdaljhmpflnnjgibpbgh";
  chrome.runtime.sendMessage(editorExtensionId, {greeting: "hello"},
    function(response) {
    console.log(response.farewell);
    });

On the background.js side right at the root:
chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
    console.log(sender.tab ?
          "from a content script:" + sender.tab.url :
          "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    }
    );

The only thing that is desirable when requesting from an injection is to make a call on a timeout, otherwise depending on the channel.

V
Vitaly Inchin ☢, 2015-08-16
@In4in

Maybe I'll say something stupid, but you mixed up the parameters in some places.
REUPD:
function(sender, request, sendResponse) {...}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question