在 content-script/background 之间发送数据
Send data between content-script/background
这是我当前的项目:
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
,以及如何让它只与活动的当前选项卡一起工作,而不是与所有打开的选项卡一起工作?这些文件在同一文件夹中。
您可以使用 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).
将消息从后台脚本发送到选项卡中的内容脚本
下面的代码将向当前选项卡中的内容脚本发送一条消息。回调版本适用于 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
entry in your manifest.json or using chrome.tabs.executeScript()
来注入内容脚本。例如,您可以使用以下方式注入脚本并发送消息(在注入脚本之后):
chrome.tabs.executeScript({
file:'core.js'
}, function(){
sendMessageToCurrentTab("test");
});
这是我当前的项目:
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
,以及如何让它只与活动的当前选项卡一起工作,而不是与所有打开的选项卡一起工作?这些文件在同一文件夹中。
您可以使用 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).
下面的代码将向当前选项卡中的内容脚本发送一条消息。回调版本适用于 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
entry in your manifest.json or using chrome.tabs.executeScript()
来注入内容脚本。例如,您可以使用以下方式注入脚本并发送消息(在注入脚本之后):
chrome.tabs.executeScript({
file:'core.js'
}, function(){
sendMessageToCurrentTab("test");
});