转换为自举:通知未定义

Converting to bootstrapped: Notification undefined

我写了一个 Firefox 附加组件,作为覆盖层工作得很好,但现在我正在将它转换为 boostrapped(无需重新启动)。它注册一个选项卡侦听器,然后在某些情况下关闭选项卡时打开 HTML5 通知。

附加调试器告诉我通知 class 未定义:

ReferenceError: 未定义通知

根据 Mozilla 文档,无需包含特殊的 JSM 即可使用通知。知道问题出在哪里,更重要的是,如何解决它?

According to the Mozilla documentation, no special JSMs need to be included to use Notifications.

这仅适用于全局对象为 DOM window 的 javascript 上下文。自举插件 run in a sandbox which only have ecmascript-defined objects (Object, Promise, ...) , Components and a few others 已定义。

检查调试器以查看该范围内到底有什么可用。

因此,如果您想使用 HTML5 API 或导入另一个服务,您要么需要检索一个 window 对象(xul windows 应该也可以)类似的功能,例如alertservice

一样,引导加载项不会自动访问全局 window 对象。这与大多数 JavaScript 是 运行 的上下文有很大不同。这是让相当多的人绊倒的事情。另外需要注意的是,bootstrap.js 中的代码在没有window的时候可能是运行ning,所以无法获取一.

如果浏览器 window 存在,您可以获得对最新浏览器 windowdocumentgBrowser 的引用:

if (window === null || typeof window !== "object") {
    //If you do not already have a window reference, you need to obtain one:
    //  Add a "/" to un-comment the code appropriate for your add-on type.
    /* Add-on SDK:
    var window = require('sdk/window/utils').getMostRecentBrowserWindow();
    //*/
    //* Overlay and bootstrap (from almost any context/scope):
    var window=Components.classes["@mozilla.org/appshell/window-mediator;1"]
                         .getService(Components.interfaces.nsIWindowMediator)
                         .getMostRecentWindow("navigator:browser");        
    //*/
}
if (typeof document === "undefined") {
    //If there is no document defined, get it
    var document = window.content.document;
}
if (typeof gBrowser === "undefined") {
    //If there is no gBrowser defined, get it
    var gBrowser = window.gBrowser;
}