浏览器扩展:在浏览器操作弹出窗口和后台脚本之间发送消息(带响应)

For*_*vin 5 javascript google-chrome-extension firefox-addon-webextensions

首先,我不是在寻找长期连接。我特别在寻找一种发送消息和直接响应这些消息的方法。

当您在 content-script 和 background-script 之间发送消息时,它非常简单,因为您使用 chrome.tabs API 从/向内容脚本发送/接收消息。并且要从/向后台脚本发送/接收消息,您可以使用 chrome.runtime API。

但是浏览器操作弹出窗口有点不同,因为两者都在后台上下文中运行。所以我想他们都必须使用 chrome.runtime API。

但这意味着我必须chrome.runtime.onMessage在浏览器操作弹出窗口和后台脚本中收听。所以基本上我会在后台脚本中接收从弹出窗口发送的消息,但也会在弹出窗口本身中接收消息。反过来也是一样。

所以是的,这真的行不通:

/////////////background-script//////////////
//Send message from background-script to browser-action-popup
chrome.runtime.sendMessage({msg:"This is a message sent from the background-script to the browser-action-popup"})
  .then(response => { //Receive response from the browser-action-popup
      console.log(response.msg)
  })

//Receive messages from browser-action-popup
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse) {
    sendResponse({msg:"This is a response message sent from the background-script"})
    return true
})
Run Code Online (Sandbox Code Playgroud)

...

///////////browser-action-popup/////////////
//Send message from browser-action-popup to background-script
chrome.runtime.sendMessage({msg:"This is a message sent from the browser-action-popup to the background-script"})
  .then(response => { //Receive response from the background-script
      console.log(response.msg)
  })

//Receive message from background-script
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse) {
    sendResponse({msg:"This is a response message sent from the browser-action-popup"})
    return true
})
Run Code Online (Sandbox Code Playgroud)

但是由于它们都在后台上下文中运行,我还想知道没有比发送消息更简单的方法了:是否可以在两者之间共享变量,或者它们是否完全隔离运行?

rsa*_*hez 2

来自文档:

如果发送到您的扩展,runtime.onMessage 事件将在您的扩展的每个帧中触发(发送者的帧除外)

因此,您不必担心弹出窗口中的消息会触发弹出窗口上的 onMessage 事件。

您还需要通过共享变量来进行另一种通信方式。从弹出窗口中,您可以调用chrome.runtime.getBackgroundPage, 来获取后台页面的 JavaScript 窗口对象。从后台页面,您可以调用chrome.extension.getViews来{type: 'popup'}访问弹出窗口的窗口对象(如果它已打开)。

Firefox文档说明getBackgroundPage:

这为其他特权附加脚本提供了一种方便的方法来直接访问后台脚本的范围。这使他们能够访问该范围内定义的变量或调用函数。这里的“特权脚本”包括在选项页面中运行的脚本,或者在浏览器操作或页面操作弹出窗口中运行的脚本,但不包括内容脚本。