【问题标题】:Chrome.runtime.onMessage returns "undefined" even when value is known for asynchronous response即使知道异步响应的值,Chrome.runtime.onMessage 也会返回“未定义”
【发布时间】:2021-12-14 18:32:02
【问题描述】:

在我的代码中,我有一个内容脚本,它从后台脚本请求一个 cookie。

即使我可以将 cookie 打印到开发工具控制台,从后台脚本接收到的消息总是未定义

为什么?

后台脚本:

// listens for content scripts to request the cookie 
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        // Respond with the value of the cookie 
        if (message === 'get-cookie') {
            chrome.cookies.get({"url": "http://www.example.com", "name": "cookie_example"}, function(cookie) {
                // prints the correct value
                console.log(cookie.value);
                sendResponse(cookie.value);
                });
             }
      });
   }
});

内容脚本:

chrome.runtime.sendMessage('get-cookie', (response) => {
    // logs "undefined"
    console.log(response);
    /* tries to do something useful with the response */
});

并返回错误

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

【问题讨论】:

    标签: asynchronous-javascript


    【解决方案1】:

    发生这种情况是因为获取 cookie 是一个异步操作。 根据documentation onMessage 返回布尔值或未定义值。由于没有返回布尔值,因此 onMessage 返回 undefined 并因错误而失败。

    要解决此问题,您必须返回一个布尔值 true 以指示 onMessage 正在返回异步响应。请记住将此类返回放在代码的最后,在任何异步请求之外。低于此回报的任何内容都将被忽略。

    注意:返回 Promise 无效。

    固定代码:

    后台脚本:

    // listens for content scripts to request the cookie 
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
            // Respond with the value of the cookie 
            if (message === 'get-cookie') {
                chrome.cookies.get({"url": "http://www.example.com", "name": "cookie_example"}, function(cookie) {
                    // prints the correct value
                    console.log(cookie.value);
                    // will send the correct value in due time
                    sendResponse(cookie.value);
                    });
                 }
          });
    
         
         return true; // CRUCIAL! indicates that an asynchronous response is being processed
    
         /* anything here will be ignored */
    
       }
    });
    

    内容脚本:

    chrome.runtime.sendMessage('get-cookie', (response) => {]
        // logs the correct value
        console.log(response);
        /* can successfully do useful things with the response */
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2017-10-18
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-02-12
      相关资源
      最近更新 更多