Chrome Extension - Message Passing Synchronously & Asynchronously

在chrome extension的文档里有这样一句话 sendResponse was called synchronously. If you want to asynchronously use sendResponse, add return true; to the onMessage event handler.

第一遍看文档的时候,刚好理解反了...后来被坑了一次,sendMessage后死活没有返回,才想起文档似乎有这么一句。

下面是一个例子:

比如在contentscript sendMessage

// in contentscript.js
chrome.runtime.sendMessage({to: 'background', subject: 'asyncCall'}, function(data){
    console.log(data);
});

background里面的监听代码如下:

chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) {
  if(request.subject == "asyncCall"){
    setTimeout(function(){
      sendResponse('called')
    }, 1000);
  }
});

但log出来的结果是undefined.
因为response需要被异步调用,而文档中说sendResponse was called synchronously.

想要返回结果,我们需要加上return true,代码如下

chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) {
  if(request.subject == "asyncCall"){
    setTimeout(function(){
      sendResponse('called')
    }, 1000);

    return true;
  }
});

你可能感兴趣的:(Chrome Extension - Message Passing Synchronously & Asynchronously)