将对象从后台脚本发送到内容脚本

时间:2014-09-06 12:42:19

标签: javascript google-chrome-extension

我正在尝试从background.js向contentscript.js发送一个对象。执行此操作的功能如下:

// 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) 

我希望有人可以帮助我,谢谢!

1 个答案:

答案 0 :(得分:1)

您将已弃用的chrome.extension.sendMessagechrome.runtime.onMessage混合在一起。这会带来各种有趣的东西。

解决方案:忘记chrome.extension.sendMessage / chrome.extension.sendRequest并且存在相应的事件。

切换到chrome.runtime.sendMessage