我在background.js中从var hello获得了响应数据,但是 在控制台中,我得到这一行“ request.greeting.text ===“ varhello”“的错误:
事件处理程序中的错误:TypeError:无法读取未定义的属性'text' 在chrome-extension://jmekelgdokcelbkancdgfgagmiopdlpl/background.js:53:30
Content.js:
var varHello = {
image_url: 'www.google.com',
text: "varhello"
};
chrome.runtime.sendMessage(
{greeting: varHello}, function(response) {
console.log(response.farewell);
});
Background.js:
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.text === "varhello"){
sendResponse({farewell: "goodbye"});
console.log(request.greeting);
}
//console.log(request.greeting.toString());
});
等待您的解决方案具有干净的控制台:-) tnx!
答案 0 :(得分:-2)
好像在某个时间点request.greeting是未定义的。采用 ?。运算符,请关注ES2020以获得更多信息,例如:request.greeting?.text
中的if (request.greeting && request.greeting.text === "varhello")