如何从页面脚本创建自定义消息的事件侦听器

how to create event listener to a custom message from page script

本文关键字:自定义消息 事件 侦听器 创建 脚本      更新时间:2023-09-26

假设一个面板被注入:

   //main.js
    var ext = require("sdk/panel").Panel({
      width: 300,
      height: 500,
      contentScriptFile: [data.url("js/angular/angular.min.js"),
                          data.url("js/angular/angular-route.js"),
                          data.url("js/app.js"),
                          data.url("js/utilities.js"),
                          data.url("js/services.js"),
                          data.url("js/directives.js"),
                          data.url("js/controllers.js"),
                          data.url("js/popup.js")],
      contentScriptWhen: "ready"
    });

我可以在活动选项卡的DOM上附加一个监听器来检测一些事件:

if(window.customObj != undefined)
{
  window.postMessage(window.customObj, window.location.href);
}

如何通过popup.jsmain.js

您的主脚本只能与内容脚本通信,包括注入选项卡的脚本和注入面板的脚本。您的内容脚本可以与主脚本和页面脚本进行通信。因此,为了从页面脚本中获得一些东西到main.js,您的路径需要是:

页面脚本/DOM-->内容脚本

内容脚本-->主脚本

以及可选的主脚本-->面板脚本