【发布时间】:2021-12-14 18:32:02
【问题描述】:
在我的代码中,我有一个内容脚本,它从后台脚本请求一个 cookie。
即使我可以将 cookie 打印到开发工具控制台,从后台脚本接收到的消息总是未定义。
为什么?
后台脚本:
// listens for content scripts to request the cookie
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Respond with the value of the cookie
if (message === 'get-cookie') {
chrome.cookies.get({"url": "http://www.example.com", "name": "cookie_example"}, function(cookie) {
// prints the correct value
console.log(cookie.value);
sendResponse(cookie.value);
});
}
});
}
});
内容脚本:
chrome.runtime.sendMessage('get-cookie', (response) => {
// logs "undefined"
console.log(response);
/* tries to do something useful with the response */
});
并返回错误
Unchecked runtime.lastError: The message port closed before a response was received
【问题讨论】: