问题
I am doing some simple tests to using one time communication between content and background.js. The code is below. I always found the error "Unchecked runtime.lastError: The message port closed before a response was received." occur in my console.log. In the below script, I made 2 step.
Step 1. give a message from background to content as soon as the browser action. Step 2. send a message back from content to background. If background received the message, it alerts.
I think the error would be triggered when the message is only send without received. But in my script, the two message are both received. Why the error still happened? I am very confused about it. I will be very thankful if anyone could tell me the reason or how to fix this.
I also did some tests. The error seems happened related to the message from content to background. Should I close or clear the port manually in the script?
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
console.log('content initial');
chrome.runtime.sendMessage({joke: "Knock knock",key:"initial from content"}, function(response) {
});
}
}
);
background.js
//initial
var tabId;
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
tabId = activeTab.id;
chrome.tabs.sendMessage(tabId, {"message": "clicked_browser_action"});
});
});
//receive
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.joke == "Knock knock"){
alert(request.key);
}
}
)
来源:https://stackoverflow.com/questions/57085797/how-to-fix-unchecked-runtime-lasterror-the-message-port-closed-before-a-respon