在内容脚本/背景之间发送数据

时间:2016-12-18 01:26:24

标签: javascript firefox firefox-webextensions

这是我目前的项目:

的manifest.json

{
  "name": "Sample Commands Extension",
  "description": "Press Ctrl+Shift+U to send an event (Command+Shift+U on a Mac).",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/commands",
  "manifest_version": 2,
  "version": "1.0",

  "background": {
    "scripts": ["background.js"]
  },

  "commands": {
    "toggle-feature": {
      "suggested_key": { "default": "Alt+Shift+U" },
      "description": "Send a 'toggle-feature' event to the extension"
    }
  }
}

background.js

    /**
     * Returns all of the registered extension commands for this extension
     * and their shortcut (if active).
     *
     * Since there is only one registered command in this sample extension,
     * the returned `commandsArray` will look like the following:
     *    [{
     *       name: "toggle-feature",
     *       description: "Send a 'toggle-feature' event to the extension"
     *       shortcut: "Ctrl+Shift+U"
     *    }]
     */
    var gettingAllCommands = browser.commands.getAll();
    gettingAllCommands.then((commands) => {
      for (command of commands) {
        console.log(command);
      }
    });

    /**
     * Fired when a registered command is activated using a keyboard shortcut.
     *
     * In this sample extension, there is only one registered command: "Ctrl+Shift+U".
     * On Mac, this command will automatically be converted to "Command+Shift+U".
     */
    browser.commands.onCommand.addListener((command) => {
      console.log("onCommand event received for message: ", command);
      // send to core.js the command?
    });

core.js

browser.runtime.onMessage.addListener(request => {
  alert(request.greeting);
});

它适用于我的键盘快捷键,我收到了我正在记录的消息。我的问题是:如何将命令发送到core.js,如何才能使其与活动的当前选项卡一起工作,而不是所有已打开的命令?这些文件位于同一文件夹中。

1 个答案:

答案 0 :(得分:2)

您可以使用tabs.sendMessage()Chrome docs)从后台脚本向选项卡中的内容脚本发送消息,您必须在其中提供您希望接收消息的选项卡的标签ID 。您无法通过一次API调用向所有选项卡广播消息。要仅发送到当前窗口中活动选项卡的选项卡,首先必须找出哪个选项卡。您可以使用tabs.query({active:true,currentWindow:true}...)Chrome docs)。

执行此操作

以下代码将向当前标签中的内容脚本发送消息。回调版本适用于Firefox或Chrome,Promises版本仅适用于Firefox(Chrome版本不实现browser.*)。

使用回调(chrome.*,可以在Chrome或Firefox中使用):

/*                   Callback based version (chrome.*)
 * Send a message to the current tab. Arguments are the same as chrome.tabs.sendMessage(),
 *   except no tabId is provided.
 *
 * sendMessageToCurrentTab(
 *     message (any) message to send
 *     options (optional object) same as tabs.sendMessage():'frameId' prop is the frame ID.
 *     callback (optional callback for response)
 * )
 */
function sendMessageToCurrentTab(){
    var args = Array.prototype.slice.call(arguments); //Get arguments as an array
    chrome.tabs.query({active:true,currentWindow:true},function(tabs){
        args.unshift(tabs[0].id); //Add tab ID to be the new first argument.
        chrome.tabs.sendMessage.apply(this,args);
    });
}

使用Promises(browser.*,可以在Firefox中使用):

/*                  Promises based version (browser.*)
 * Send a message to the current tab. Arguments are the same as browser.tabs.sendMessage(),
 *   except no tabId is provided.
 *
 * sendMessageToCurrentTab(
 *     message (any) message to send
 *     options (optional object) same as tabs.sendMessage():'frameId' prop is the frame ID.
 * )
 */
function sendMessageToCurrentTab(){
    var args = Array.prototype.slice.call(arguments); //Get arguments as an array
    return browser.tabs.query({active:true,currentWindow:true}).then(function(tabs){
        args.unshift(tabs[0].id); //Add tab ID to be the new first argument.
        return browser.tabs.sendMessage.apply(this,args);
    });
}

首先需要注入内容脚本

但是,在能够向内容脚本发送消息之前,需要在页面中注入内容脚本。您需要使用content_scripts中的manifest.json条目或使用chrome.tabs.executeScript()来注入内容脚本。例如,您可以使用以下命令注入脚本并发送消息(在注入脚本之后):

chrome.tabs.executeScript({
    file:'core.js'
}, function(){
    sendMessageToCurrentTab("test");
});