gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:53:39 25 4
gpt4 key购买 nike

我正在尝试将一个对象从我的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)

希望有人能帮我解决这个问题,谢谢!

最佳答案

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

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

切换到chrome.runtime.sendMessage

关于javascript - 将对象从后台脚本发送到内容脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25700388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com