在内容脚本/背景之间发送数据 [英] Send data between content-script/background

查看:156
本文介绍了在内容脚本/背景之间发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我当前的项目:
$ b

manifest.json

<$ p
name:Sample Commands Extension,
description:按Ctrl + Shift + U发送一个事件(Command + Shift + U on一个Mac),
homepage_url:https://github.com/mdn/webextensions-examples/tree/master/commands,
manifest_version:2,
version:1.0,

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

{
toggle-feature:{
suggested_key:{default:Alt + Shift + U},
description:发送'切换功能'事件到扩展名

}
}





  / ** 
*返回所有的注册扩展命令为这个扩展
*和他们的快捷方式(如果活动)。
*
*由于在这个示例扩展中只有一个注册命令,
*返回的`commandsArray`如下所示:
* [{
*名称:toggle-feature,
* description:发送'toggle-feature'事件到扩展名
*快捷键:Ctrl + Shift + U
*}]
* /
var gettingAllCommands = browser.commands.getAll();
gettingAllCommands.then((commands)=> {
for(command of command){
console.log(command);
}
});

/ **
*使用键盘快捷键激活注册命令时触发。
*
*在这个示例扩展中,只有一个注册的命令:Ctrl + Shift + U。
*在Mac上,此命令将自动转换为Command + Shift + U。

browser.commands.onCommand.addListener((command)=> {
console.log(onCommand event for message:,command);
/ /发送到core.js的命令?
});

core.js

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

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

解决方案

您可以使用后台脚本将消息发送到选项卡中的内容脚本 tabs.sendMessage() Chrome文档),以您必须提供您希望接收邮件的标签的标签ID。只有一个API调用,您无法将消息广播到所有选项卡。要仅发送到当前窗口中活动选项卡的选项卡,首先必须找出哪个选项卡是。您可以使用 标签页.query({active:true,currentWindow:true} ...) Chrome docs )。 回调版本可以在Firefox或Chrome中运行,Promises版本只能在Firefox中运行(Chrome浏览器不实现 browser。* )。

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

  / *基于回调的版本(chrome。*)
*发送消息到当前选项卡。参数与chrome.tabs.sendMessage(),
*相同,只是没有提供tabId。
*
* sendMessageToCurrentTab(
* message(any)message to send
* options(可选对象)与tabs.sendMessage()相同:'frameId'prop是框架ID
* callback(可选的回应回调函数)
*)
* /
函数sendMessageToCurrentTab(){
var args = Array.prototype.slice.call ); //获取参数作为数组
chrome.tabs.query({active:true,currentWindow:true},function(tabs){
args.unshift(tabs [0] .id); //添加标签ID作为新的第一个参数
chrome.tabs.sendMessage.apply(this,args);
});





使用Promise( browser。*

/ * Promises based version(browser。* )
*发送消息到当前标签。参数与browser.tabs.sendMessage(),
*相同,只是没有提供tabId。
*
* sendMessageToCurrentTab(
* message(any)message to send
* options(可选对象)与tabs.sendMessage()相同:'frameId'prop是框架ID 。
*)
* /
函数sendMessageToCurrentTab(){
var args = Array.prototype.slice.call(arguments); //获取参数作为数组
返回browser.tabs.query({active:true,currentWindow:true})。then(function(tabs){
args.unshift(tabs [0] .id ); //添加标签ID作为新的第一个参数
return browser.tabs.sendMessage.apply(this,args);
});

$ / code>



需要先注入内容脚本



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

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


This is my current project:

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

it works with my keyboard shortcut, I get that message I'm logging. My question is: how can I send the command to the core.js, and how can I make it work just with the active current tab one, and not with all the opened ones? The files are on the same folder.

解决方案

You can send a message from the background script to content scripts in a tab by using tabs.sendMessage() (Chrome docs), to which you must provide the tab ID of the tab you wish to receive the message. You can not broadcast a message to all tabs with one API call. To send to only the tab that is the active tab in the current window, you first have to find out which tab that is. You can do that with tabs.query({active:true,currentWindow:true}...) (Chrome docs).

The code below will send a message to the content script in the current tab. The callback version works in either Firefox or Chrome, the Promises version only works in Firefox (Chrome doe not implement browser.*).

Using callbacks (chrome.*, can use in Chrome or 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);
    });
}

Using Promises (browser.*, can use in 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);
    });
}

Need to inject the content script first

However, prior to being able to send a message to a content script, the content script needs to be injected in the page. You will need to inject the content script by either using a content_scripts entry in your manifest.json or using chrome.tabs.executeScript(). For example, you could inject the script and send the message (after the script is injected) using:

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

这篇关于在内容脚本/背景之间发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆