发布时间:2023-04-21 文章分类:WEB开发, 电脑百科 投稿人:赵颖 字号: 默认 | | 超大 打印

文章目录

  • 1. 文章引言
  • 2. 分析问题
  • 3. 解决问题
  • 4. 解决该错误的其他方法

1. 文章引言

今天启动项目后访问Knife4j接口文档,却报出下图错误:

全网多种方式解决Unchecked runtime.lastError: The message port closed before a response was received的错误

在报出Knife4j文档请求异常错误时,赶紧打开控制台,如下所示:

全网多种方式解决Unchecked runtime.lastError: The message port closed before a response was received的错误

Unchecked runtime.lastError: The message port closed before a response was received.

2. 分析问题

正赶上最近ChatGPT很火,于是借助ChatGPT来解决我的问题,如下所示:

全网多种方式解决Unchecked runtime.lastError: The message port closed before a response was received的错误

Unchecked runtime.lastError: The message port closed before a response was received.

This error occurs when a message port fails to respond within a specified time frame, which means that the browser was unable to send data or receive a response from the server. This could be caused by an issue with the connection between the browser and the server, an issue with the server, or an issue with the messaging system between the browser and the server.

不巧的是,给出的是英文回复,我们可以将其翻译成中文,如下所示:

当消息端口无法在指定的时间范围内响应时,会发生此错误,这意味着浏览器无法发送数据或接收来自服务器的响应。这可能是由浏览器和服务器之间的连接问题、服务器问题或浏览器和服务器之间的邮件系统问题引起的。

简单理解ChatGPT的回复,即服务端无法在指定时间内,给到客户端的响应。

如果客户端的代码引入某一插件(比如vue,react等),而该插件中某一脚本页在接不到响应时,又使用了chrome.runtime.sendMessage或者tabs.sendMessage并调用了回调函数而接收函数并没调用导致的。

为了验证这个错误,我们使用node.js来写一段简单前后端代码,如下所示。

  1. 前端的简单代码(front-script.js):
//ront-script.js简单代码
chrome.runtime.sendMessage({
    action: "server",
    source: "test Unchecked runtime.lastError",
},function(e){
    alert('ok');
});

上面的函数发送了test Unchecked runtime.lastError消息,并调用了回调函数用来alter(‘ok’)

  1. 后端的简单代码(backend.js):
//backend.js简单代码
chrome.extension.onMessage.addListener(
  function (request, sender, sendResponse) {
	if (request.action === "server") {
		var a= 0;
	}
  } 
);

如果后端只处理逻辑,并不调用回调函数sendResponse(),就会出现这个错误:Unchecked runtime.lastError: The message port closed before a response was received.

3. 解决问题

backend.js中正确的处理方法是:

// backend.js正确的代码
chrome.extension.onMessage.addListener(
  function (request, sender, sendResponse) {
    if (request.action === "server") {
	   var a= 0;
	 //注意就是这个sendResponse函数一定要调用,否则就会报错
	  sendResponse({farewell: "ok"});  
    } 
  }
);

也就是说sendResponse({farewell: "ok"})这一段不调用的话就会报这个错误:Unchecked runtime.lastError: The message port closed before a response was received

但是很多情况下并没有调用,而发送函数自己却使用到了,从而导致这个错误。

如果上述方法无法解决你的问题,可以参考下面的解决方法。

4. 解决该错误的其他方法

如果你在chrome中引入了某一扩展程序,比如vueVideo Speed Master等,有可能会因为插件和程序不兼容导致这个错误:Unchecked runtime.lastError: The message port closed before a response was received

解决方法:只要在chrome://extensions/里面把这个阅读模式关闭就可以,如下图所示:

全网多种方式解决Unchecked runtime.lastError: The message port closed before a response was received的错误

全网多种方式解决Unchecked runtime.lastError: The message port closed before a response was received的错误

如果还是无法解决你的问题,欢迎在评论区中留言。

如果你的错误不是通过以上方法解决的,也欢迎在评论区中留言。