Firefox JPM -从制表符调用外部发出制表符



在本文档中有一个如何向选项卡发出数据/事件的示例。以下是我编辑后的版本:

success-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

试试这个。不要忘记调整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;
   }
});

你试过这样设置全局变量吗:

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

相关内容

  • 没有找到相关文章

最新更新