正在转换为引导:未定义通知

Converting to bootstrapped: Notification undefined

本文关键字:未定义 通知 转换      更新时间:2023-09-26

我写了一个Firefox插件,它可以很好地用作覆盖,但现在我正在将其转换为boostrapped(restartless)。它注册一个选项卡侦听器,然后在某些情况下关闭选项卡时打开HTML5通知。

附加调试程序告诉我Notification类是未定义的:

ReferenceError:未定义通知

根据Mozilla文档,使用通知不需要包含任何特殊的JSM。知道问题是什么吗?更重要的是,知道如何解决吗?

根据Mozilla文档,使用通知不需要包含任何特殊的JSM。

这只适用于全局对象是DOM窗口的javascript上下文。自举插件在沙盒中运行,沙盒中只定义了ecmascript定义的对象(ObjectPromise、…)、Components和其他一些对象。

请与调试器进行检查,以查看该作用域中究竟有什么可用。

因此,如果您想要使用HTML5 API,您要么需要检索窗口对象(xul-windows也应该工作),要么导入其他具有类似功能的服务,例如alertservice

正如8472所述,引导加载项不会自动访问全局window对象。这与大多数JavaScript运行的上下文有很大不同。这是一件让相当多的人感到困惑的事情。还应该注意的是,bootstrap.js中的代码可能在不存在窗口的时候运行,因此您无法获得窗口。

如果存在浏览器窗口,您可以通过以下方式获得对最新浏览器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;
}