如何在Firefox插件中实现Chrome扩展的chrome.tabs.sendMessage API [英] how to implement Chrome extension 's chrome.tabs.sendMessage API in Firefox addon

查看:381
本文介绍了如何在Firefox插件中实现Chrome扩展的chrome.tabs.sendMessage API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Addon-Builder开发Firefox插件。我不知道如何在Firefox插件中实现Chrome扩展的chrome.tabs.sendMessage API。代码是这样的(代码在background.js中,类似于Firefox插件中的main.js):

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





$ b所以,我该如何做到这一点?谢谢。

解决方案

在使用附加SDK构建的附加组件中,内容脚本由main.js管理。没有内置的方式来访问您的所有附加的内容脚本。要发送消息到所有标签页,您需要手动跟踪内容脚本。

单向消息很容易通过现有的API 。虽然回调不是内置的。



我的浏览器动作SDK库包含一个名为 messaging ,它实现了Chrome消息传递API。在以下示例中,内容脚本和主脚本使用名为extension的对象。这个对象暴露了 onMessage sendMessage 方法,模仿Chrome扩展 messaging API。



以下示例向每个页面添加内容脚本堆栈溢出,点击后,标签的标题将被记录到控制台(使用 Ctrl + Shift + J 打开)。

lib / main.js



  // https://github.com/Rob--W/browser-action-jplib/blob/master/lib/messaging.js 
const {createMessageChannel,messageContentScriptFile} = require( '消息');
const {PageMod} = require('sdk / page-mod');
const {data} = require('sdk / self');

//将消息API添加到加载项
var ports = []中的每个页面;
var pagemod = PageMod({
include:['http://stackoverflow.com/*'],
contentScriptWhen:'start',
contentScriptFile:[messageContentScriptFile,data .url('contentscript.js')],
contentScriptOptions:{
channelName:'你想要的',
endAtPage:false
},
onAttach:function (worker){
var extension = createMessageChannel(pagemod.contentScriptOptions,worker.port);
ports.push(extension);
worker.on('detach',function(){$
var index = ports.indexOf(extension);
if(index!== -1)ports.splice(index ,1);
});
}
});
函数sendMessageToTabs(message,callbackFunc){
for(var i = 0; i ports [i] .sendMessage(message,callbackFunc);



//因为我们已经包含了浏览器动作模块,所以我们可以在演示
var badge = require('browserAction' ).BrowserAction({
default_title:'点击发送消息到堆栈溢出的所有标签'
});
badge.onClicked.addListener(function(){
sendMessageToTabs('gimme title',function(response){
//使用console.error确保日志在
console.error(response);
});
});

记录中, main.js onAttach 事件中。
$ b

data / contentscript.js code $
$ b $ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ message ==='gimme title'){
sendResponse(document.title);
}
});


I'm working on a Firefox addon development with Addon-Builder.I have no idea about how to implement Chrome extension 's chrome.tabs.sendMessage API in Firefox addon. The code is like this(the code is in the background.js, something like main.js in the Firefox addon):

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

So,How can I achieve this?Thanks.

解决方案

In add-ons build using the Add-on SDK, content scripts are managed by main.js. There's no built-in way to access all of your add-on's content scripts. To send a message to all tabs, you need to manually keep track of the content scripts.

One-way messages are easily implemented by the existing APIs. Callbacks are not built-in, though.

My browser-action SDK library contains a module called "messaging", which implements the Chrome messaging API. In the following example, the content script and the main script use an object called "extension". This object exposes the onMessage and sendMessage methods, modelled after the Chrome extension messaging APIs.

The following example adds a content script to every page on Stack Overflow, and upon click, the titles of the tabs are logged to the console (the one opened using 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);
    });
});

For the record, the interesting part of main.js is inside the onAttach event.

data/contentscript.js

extension.onMessage.addListener(function(message, sender, sendResponse) {
    if (message === 'gimme title') {
        sendResponse(document.title);
    }
});

这篇关于如何在Firefox插件中实现Chrome扩展的chrome.tabs.sendMessage API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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