• content-script 发送消息给background : runtime.lastError: The message port closed before a response was received.


    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(),

    解决方法:

    相关链接:https://stackoverflow.com/questions/54126343/how-to-fix-unchecked-runtime-lasterror-the-message-port-closed-before-a-respon/56483156#56483156

    修改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).

    个人推荐
    萨哈拉单板滑雪 https://sahala.suanhetao.com
  • 相关阅读:
    传球游戏(NOIP2008 普及组第三题)
    立体图(NOIP2008 普及组第四题)
    多项式输出(NOIP2009 普及组第一题)
    分数线划定(NOIP2009 普及组第二题)
    第5到8章
    第四章总结
    实验九
    实验五
    实验四
    实验三
  • 原文地址:https://www.cnblogs.com/michaelluthor/p/11957667.html
Copyright © 2020-2023  润新知