pen*_*hou 3 tabs firefox-addon google-chrome-extension dom-events firefox-addon-sdk
我正在使用Addon-Builder进行Firefox插件开发.我不知道如何在Firefox插件中实现Chrome扩展程序的chrome.tabs.sendMessage API.代码是这样的(代码在background.js中,类似于Firefox插件中的main.js):
function sendMessageToTabs(message, callbackFunc){
chrome.tabs.query({}, function(tabsArray){
for(var i=0; i<tabsArray.length; i++){
//console.log("Tab id: "+tabsArray[i].id);
chrome.tabs.sendMessage(tabsArray[i].id,message,callbackFunc);
}
});
}
Run Code Online (Sandbox Code Playgroud)
那么,我怎样才能做到这一点?
在使用Add-on SDK构建的附加组件中,内容脚本由main.js管理.没有内置方法可以访问所有加载项的内容脚本.要向所有选项卡发送消息,您需要手动跟踪内容脚本.
现有API可以轻松实现单向消息.但是,回调不是内置的.
我的浏览器动作SDK库包含一个名为" messaging " 的模块,该模块实现了Chrome消息传递API.在以下示例中,内容脚本和主脚本使用名为"extension"的对象.此对象公开了以Chrome扩展消息传递 API 为模型的方法onMessage和sendMessage方法.
以下示例将内容脚本添加到Stack Overflow上的每个页面,单击后,选项卡的标题将记录到控制台(使用Ctrl+ Shift+ 打开的标题J).
lib/main.js// https://github.com/Rob--W/browser-action-jplib/blob/master/lib/messaging.js
const { createMessageChannel, messageContentScriptFile } = require('messaging');
const { PageMod } = require('sdk/page-mod');
const { data } = require('sdk/self');
// Adds the message API to every page within the add-on
var ports = [];
var pagemod = PageMod({
include: ['http://stackoverflow.com/*'],
contentScriptWhen: 'start',
contentScriptFile: [messageContentScriptFile, data.url('contentscript.js')],
contentScriptOptions: {
channelName: 'whatever you want',
endAtPage: false
},
onAttach: function(worker) {
var extension = createMessageChannel(pagemod.contentScriptOptions, worker.port);
ports.push(extension);
worker.on('detach', function() {
// Remove port from list of workers when the content script is deactivated.
var index = ports.indexOf(extension);
if (index !== -1) ports.splice(index, 1);
});
}
});
function sendMessageToTabs(message, callbackFunc) {
for (var i=0; i<ports.length; i++) {
ports[i].sendMessage(message, callbackFunc);
}
}
// Since we've included the browser-action module, we can use it in the demo
var badge = require('browserAction').BrowserAction({
default_title: 'Click to send a message to all tabs on Stack Overflow'
});
badge.onClicked.addListener(function() {
sendMessageToTabs('gimme title', function(response) {
// Use console.error to make sure that the log is visible in the console.
console.error(response);
});
});
Run Code Online (Sandbox Code Playgroud)
为了记录,有趣的部分main.js是在onAttach事件中.
data/contentscript.jsextension.onMessage.addListener(function(message, sender, sendResponse) {
if (message === 'gimme title') {
sendResponse(document.title);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2659 次 |
| 最近记录: |