Chrome.runtime.onMessage returns "undefined" 即使异步响应的值已知

Chrome.runtime.onMessage returns "undefined" even when value is known for asynchronous response

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

即使我可以将 cookie 打印到 Dev Tool 控制台,从后台脚本 收到的消息始终是 undefined

为什么?

后台脚本:

// 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 */
});

并且returns一个错误

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

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

要解决该问题,您必须return一个布尔值true来指示onMessage 是return异步响应。请记住将这样的 return 放在代码的最后,在任何异步请求之外。低于 return 的任何内容都将被忽略。

注意:返回 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 */
});