0

I am trying to sent a object from my background.js to contentscript.js. The functions that do this are these:

// contentscript.js

chrome.extension.sendMessage({ message: 'getdata' }, function(response) {
    console.log(response.data); // Object {}
    console.log(response.data.property); // ERROR (see below)
});

-

// background.js
var data = { property: 'test' };

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.message === 'getdata') {
            sendResponse({ data: data });
        }
    }
);

-

The error: 
Error in event handler for (unknown): Cannot read property 'property' of undefined
Stack trace: TypeError: Cannot read property 'property' of undefined
    at chrome-extension://neneohfdjobjkpbdmapenhmpmofmnmpo/scripts/contentscript.js:99:70
    at messageListener (extensions::messaging:343:9)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at EventImpl.dispatchToListener (extensions::event_bindings:397:22)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at Event.$Array.forEach.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:93:26)
    at EventImpl.dispatch_ (extensions::event_bindings:379:35)
    at EventImpl.dispatch (extensions::event_bindings:403:17)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at Event.$Array.forEach.publicClass.(anonymous function) [as dispatch] (extensions::utils:93:26) 

I hope someone can help me with this, thanks!

1 Answer 1

1

You mixed together the deprecated chrome.extension.sendMessage and chrome.runtime.onMessage. This leads to all kinds of fun stuff.

Solution: forget that chrome.extension.sendMessage/chrome.extension.sendRequest and corresponding events exist.

Switch to chrome.runtime.sendMessage

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm, that is a good catch. But it did not solve my problem. Still getting the same error message.
Then I recommend you to double-check for typos in variables and string constants. Also, run a debugger on your background script to ensure data is being sent.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.