美文网首页
Chrome Extension - Message Passi

Chrome Extension - Message Passi

作者: 我要走多远 | 来源:发表于2016-11-22 22:19 被阅读111次

    在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 Passi

          本文链接:https://www.haomeiwen.com/subject/klempttx.html