During the Chrome extension development process, we may encounter a common error message: "The message port closed before a response was received.". This error usually occurs when we try to chrome.runtime.onMessage
send a response asynchronously in a listener. In this blog, we will explore what causes this error and how to fix it.
Problem Description
In a Chrome extension project, we may need to send and receive messages between a background script and a content script. We will typically use chrome.runtime.sendMessage
the and chrome.runtime.onMessage
API to achieve this. However, when we try to chrome.runtime.onMessage
send a response asynchronously in a listener, we may encounter "The message port closed before a response was received." error.
wrong reason
This error usually occurs because chrome.runtime.onMessage
the listener closed the message port before the asynchronous operation completed, preventing the response from being sent.
Solution
Method 1: Use return true
We can keep the message port open until the asynchronous operation completes and the response is sent by returningchrome.runtime.onMessage
in the listener .true
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
handleAsyncMessage(message, sendResponse);
return true; // Indicate that response will be sent asynchronously
});
async function handleAsyncMessage(message, sendResponse) {
// ...异步操作...
sendResponse({
/* response data */ });
}
Method 2: Dual listener strategy
Another solution is to use two chrome.runtime.onMessage
listeners. One listener returns immediately true
to keep the message port open, and the other listener handles the actual messages and asynchronous operations.
// 第一个监听器,立即返回 true 以保持消息端口开启
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return true; // Indicate that response will be sent asynchronously
});
// 第二个监听器,处理实际的消息和异步操作
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
// ...异步操作...
sendResponse({
/* response data */ });
});
Method 3: Check the status of the message sender
Make sure the message sender (such as a popup or content script) remains active until a response is received.
in conclusion
Through the above method, we can effectively solve the "The message port closed before a response was received." error and ensure that our Chrome extension can correctly handle asynchronous messages and responses.