firefox jpm - 从tab外部发出标签

时间:2015-08-17 09:01:30

标签: javascript firefox firefox-addon firefox-addon-sdk jpm

this documentation中,有一个如何向选项卡发出数据/事件的示例。这是我编辑的版本:

成功-window.js

// "self" is a global object in content scripts
// Listen for a "drawBorder"
self.port.on("drawBorder", function(color) {
  document.body.style.border = "5px solid " + color;
});

index.js

var self = require("sdk/self");
var tabs = require("sdk/tabs");

var success_tab;
var myTab = tabs.open({
    url: data.url("success-window.html"),
    onReady: function onReady(tab) {
        success_tab = tab.attach({
            contentScriptFile: [data.url('angular/angular.min.js'),
                data.url('angular-bootstrap/ui-bootstrap-tpls.min.js'),
                data.url('success-window.js')]
        });
    }
});

如何在按钮定义之外使用success_tab.port.emit? 与 index.js 中的另一个函数一样,例如console.log

console.log('mytab:', myTab); // mytab: undefined
console.log('success_tab:', success_tab); // success_tab: undefined
success_tab.port.emit("drawBorder", "red"); // JPM [error]   Message: TypeError: success_tab is undefined

2 个答案:

答案 0 :(得分:2)

试试这个。不要忘记调整include以匹配您的成功html页面命名如下:

var self = require("sdk/self");
var tabs = require("sdk/tabs");
var mods = require("sdk/page-mod");

var successWorker;

mods.PageMod({
    include: "*", //adjust this to match ONLY your success page
    contentScriptWhen:'start',
    contentScriptFile: [data.url('angular/angular.min.js'),
                        data.url('angular-bootstrap/ui-bootstrap-tpls.min.js'),
                        data.url('success-window.js')],
    onAttach: function(worker){

        successWorker= worker;

        worker.on("message", function(aData){
            //messages from success-window.js
        });

        worker.on("detach", function(){
            //prevent worker from being used after it's been disposed
            successWorker= undefined;
        });
    }
});

function postToSuccessWindow(message){
    if(successWorker){
        successWorker.postMessage(message);
    }
}

此外,拨打tabs.open的电话不会返回标签。要引用该选项卡,您必须这样做:

var successTab;

tabs.open({
   url: "success-window.html"
   onOpen: function(tab){
    successTab = tab;
   }
});

答案 1 :(得分:0)

您是否尝试将其设置为这样的全局:

var self = require("sdk/self");
var tabs = require("sdk/tabs");

var worker;
var button = require("sdk/ui/button/action").ActionButton({
  id: "style-tab",
  label: "Style Tab",
  icon: "./icon-16.png",
  onClick: function() {
    worker = tabs.activeTab.attach({
      contentScriptFile: self.data.url("my-script.js")
    });
    worker.port.emit("drawBorder", "red");
  }
});