Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从后台脚本处理内容脚本中的回调?_Javascript_Google Chrome Extension - Fatal编程技术网

Javascript 如何从后台脚本处理内容脚本中的回调?

Javascript 如何从后台脚本处理内容脚本中的回调?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,我正在向后台脚本发送消息并在侦听器中接收数据 在内容脚本中 我需要从监听器调用sendData的回调函数。 在内容脚本和后台脚本之间有多个消息和进程。请帮忙。 在这里,后台脚本返回的格式是chrome.runtime.sendMessage。消息只是JSON;它们不能包含函数。在内容脚本中,保存对回调函数的引用,然后在内容脚本和后台脚本之间传递消息时包含该id。完成所有中间处理后,发送一条消息,告诉内容脚本运行回调。当内容脚本接收到带有回调id的消息时,查找回调函数并调用它 内容脚本 背景脚本

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

在内容脚本中

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

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

内容脚本

背景脚本


正如问题中指定的,发送的消息应该是对象{data:formdata,method:'storeform'},但是

简单、通用的示例 在下面的示例中,消息是字符串“Hello background script!”

函数sendMessageFromTab{ 常量脚本=` 作用{ const message='Hello background script!'; chrome.runtime.sendMessagemessage; }; `; chrome.tabs.executeScript{ 代码:脚本 }; } 函数listenForMessages{ chrome.runtime.onMessage.addListenermessage=>{ console.log'receivemessage:',message; }; } chrome.browserAction.onClicked.addListener=>{ //^运行代码,例如,单击扩展的图标时 列表信息; sendMessageFromTab; };
是否尝试将回调函数作为最后一个参数传递给侦听器?我的意思是,如果你想执行回调,只要传递它就行了。可能吗?因为这是两种不同的功能。secone是从后台脚本调用的。我想知道如何将回调函数作为参数传递到后台脚本。第二个函数不是从后台脚本调用的,它是从内容脚本本身调用的,而是在后台脚本向内容脚本发送消息时发生的。确切地说。当后台脚本发送消息时,侦听器被触发。我需要调用Listener中方法1的回调。您的回调函数位于哪里?
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

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