How to fix “Unchecked runtime.lastError: The message port closed before a response was received.” in self made chrome extension?

旧街凉风 提交于 2019-12-24 21:50:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!