在Chrome extension中,当使用chrome.runtime.sendMessage()
或chrome.tabs.sendMessage()
向content script发送消息时,有时会出现以下错误:
The message port closed before a response was received.
这个错误通常是由于content script在接收到消息后,在回复消息之前,已经被注销或关闭了。
解决这个问题的方法是,在你的content script中添加一个检查,确保在发送回复消息之前,消息端口仍然存在。
示例代码:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(sender.tab && sender.tab.id && sender.url && request.action === "my-message") {
// do something here
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
}
// check if port is still open
try {
if(sender.tab.id && sender.url && sendResponse) {
sendResponse({message: "success"});
}
}
catch(error) {
console.error(error);
}
}
});
这个代码片段检查sendResponse
函数是否存在,并且尝试在检查之前使用chrome.runtime.lastError
查看是否出现任何其他错误。
需要注意的是,如果已经关闭了消息端口,调用sendResponse
函数会引发另一个错误,因此需要使用try-catch块来捕获这个错误。
如果你经常遇到这种错误,你可能需要重新审视你的content script,看看是否有必要在消息端口被注销或关闭之前立即进行处理。