【问题标题】:Firefox Add-On window.navigator.userAgent error: window not definedFirefox 附加组件 window.navigator.userAgent 错误:未定义窗口
【发布时间】:2023-03-28 16:03:01
【问题描述】:

我正在尝试获取userAgent 并想对其进行一些解析:

我的代码是:

var userAgentInfo = {
    userAgent: null,

    init: function() {
        this.userAgent = window.navigator.userAgent;//ERROR
    },

    getOS: function(UA) {
        //Some logic
    },

    getDevice: function(UA) {
        //Some logic
    },
    getBrowser: function(UA) {
        //Some logic
    },
};

每当我尝试启动/测试此扩展时,我都会收到以下错误:

Running tests on Firefox 24.3.0/Gecko 24.3.0 ({ec8030f7-c20a-464f-9b0e-13a3a9e97384}) under linux/x86-gcc3.
Error: ReferenceError: window is not defined 
 Traceback (most recent call last):
  File "resource://jid1-u33krawc1uacsa-at-jetpack/amazon_rewriter/tests/test-main.js", line 1, in 

如何在不获取窗口和导航器对象的情况下在此处获取userAgent

【问题讨论】:

  • 顺便说一句:Firefox 24.3.0 在这一点上已经很老了。你使用它是因为它是一个 ESR 并且你需要一些特定的功能吗?您可能想要升级/更新到当前版本。

标签: javascript firefox firefox-addon firefox-addon-sdk


【解决方案1】:

Firefox 附加组件通常在未定义全局 window 对象的范围内运行(是否定义取决于当前运行的代码部分是如何输入的)。如果要使用与窗口对象关联的方法/对象,最简单的方法是获取对适当window 对象的引用。对于某些/许多事情,可以在不获取此类引用的情况下这样做,但通常更容易获取对最新浏览器窗口的引用。

如果存在浏览器窗口(在某些情况下,您可能在不存在浏览器窗口的情况下运行,例如在启动时),您可以获得对最新浏览器 windowdocumentgBrowser 与:

if (window === null || typeof window !== "object") {
    //If you do not already have a window reference, you need to obtain one:
    //  Add/remove a "/" to comment/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;
}

缺少可用的全局 window 对象是许多人遇到的问题。

参考资料:

  1. SDK:window/utils
  2. SDK:windows
  3. nsIWindowMediator
  4. Working with windows in chrome code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多