1

本文档中,有一个如何将数据/事件发送到选项卡的示例。这是我编辑的版本:

成功-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
4

2 回答 2

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;
   }
});
于 2015-08-17T10:01:23.807 回答
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");
  }
});
于 2015-08-17T09:02:34.877 回答