【问题标题】:How to handle callback in content script from background script?如何从后台脚本处理内容脚本中的回调?
【发布时间】:2017-10-20 17:07:26
【问题描述】:

我正在向后台脚本发送消息并在侦听器中接收数据,

在内容脚本中”

function sendData(formdata,callback){
  chrome.runtime.sendMessage({data: formdata, method:
 'storeform'},function(response) {
              console.log(response.data);   
 });
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) { 
     if(request.method == "storeform")
     {
        //do some work

        });             
    }

我需要从监听器调用 sendData() 的回调函数。 在内容脚本和后台脚本之间有多个消息和进程。请帮忙。 这里从后台脚本返回是 chrome.runtime.sendMessage 的形式。

【问题讨论】:

  • 您是否尝试将回调作为最后一个参数传递给 Listener 函数?我的意思是,如果您想很好地执行回调,只需传递它即可。
  • 有可能吗?因为这是两个不同的功能。第二个是从后台脚本调用的。我想知道如何将回调函数作为参数传递给后台脚本。
  • 第二个不是从后台脚本调用的,它是从内容脚本本身调用的,但是当后台脚本向内容脚本发送消息时发生事件。
  • 完全正确。当后台脚本发送消息时,监听器被触发。我需要在监听器中调用方法1的回调
  • 你的回调函数位于哪里?

标签: javascript google-chrome-extension


【解决方案1】:

消息只是 JSON;它们不能包含函数。在内容脚本中,保存对回调函数的引用,然后在内容和后台脚本之间传递消息时包含该 id。完成所有中间处理后,发送一条消息告诉内容脚本运行回调。当内容脚本收到带有回调 id 的消息时,查找回调函数并调用它。

内容脚本

var callbacks = {};

function sendData(formdata, callback) {
  // good-enough unique id
  var callbackId = (new Date()).getTime();
  callbacks[callbackId] = callback;
  chrome.runtime.sendMessage({
      data: formdata,
      method: 'storeform',
      callbackId,
  }, function(response) {
      console.log(response.data);   
  });
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) { 
     // if message includes a callback id, call it
     if (request.callbackId && callbacks[request.callbackId]) {
         callbacks[request.callbackId]();
     }
  }          
)

后台脚本

// everything done; call the callback
chrome.runtime.sendMessage({callbackId});

【讨论】:

    【解决方案2】:

    按照问题中的说明,发送的message应该是一个对象({data: formdata, method: 'storeform'}),但是你can send any messages that you can JSON.stringify

    简单、通用的例子

    在下面的示例中,消息是字符串'Hello background script!'

    function sendMessageFromTab() {
        const script = `
            (function() {
                const message = 'Hello background script!';
    
                chrome.runtime.sendMessage(message);
            })();
        `;
    
        chrome.tabs.executeScript({
            code: script
        });
    }
    
    function listenForMessages() {
        chrome.runtime.onMessage.addListener((message) => {
            console.log('Received message:', message);
        });
    }
    
    
    chrome.browserAction.onClicked.addListener(() => {
        // ^ Run the code e.g. when clicking the icon of the Extension
        listenForMessages();
        sendMessageFromTab();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      相关资源
      最近更新 更多