content-script内容
chrome.runtime.sendMessage("消息内容", function(response) { alert(response); });
background 内容
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { $.post("https://example.com", {key:1}, function( response ) { sendResponse(response); },'json'); });
出现的问题:
当background js的post请求开始后,content-script 直接得到了response,并且取值undefined, 并没有等到background中的post完成后回调sendResponse(),
解决方法:
修改background中的内容, 在接收消息的事件处理器上加个 return true; 来保证sendResponse的有效性, 修改后内容
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { $.post("https://example.com", {key:1}, function( response ) { sendResponse(response); },'json'); return true; });
原文内容:
In case you're an extension developer and have googled your way here trying to stop causing this error:
The issue isn't CORB, as blocked CORs manifest as warnings like -
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.example.com/example.html with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
The issue is most likely a mishandled async response to runtime.sendMessage. As MDN says:
To send an asynchronous response, there are two options:
- return true from the event listener. This keeps the sendResponse function valid after the listener returns, so you can call it later.
- return a Promise from the event listener, and resolve when you have the response (or reject it in case of an error).
When you send an async response but fail to use either of these mechanisms, the supplied sendResponse
argument to sendMessage
goes out of scope and the result is exactly as the error message says: your message port (the message-passing apparatus) is closed before the response was received.
Webextension-polyfill authors have already written about it in June 2018.
So bottom line, if you see your extension causing these errors - inspect closely all your onMessage listeners. Some of them probably need to start returning promises (marking them as async should be enough).