Firefox 附加组件 window.navigator.userAgent 错误:窗口未定义 [英] Firefox Add-On window.navigator.userAgent error: window not defined
问题描述
我正在尝试获取 userAgent
并想对其进行一些解析:
I am trying to get userAgent
and want to do some parsing on it:
我的代码是:
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
},
};
每当我尝试启动/测试此扩展时,都会收到以下错误:
Whenever I try to start/test this extension I receive the following error:
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
此处?
How I can get userAgent
here without getting window and navigator object?
推荐答案
Firefox 附加组件通常在未定义全局 window
对象的范围内运行(是否定义取决于输入了当前正在运行的代码部分).如果您想使用与 window 对象关联的方法/对象,最简单的方法是获取对适当 window
对象的引用.对于某些/许多事情,可以在不获得此类引用的情况下执行此操作,但通常更容易获得对最新浏览器窗口的引用.
Firefox add-ons generally run in a scope where the global window
object is not defined (if it is defined depends on how the portion of your code that is currently running was entered). If you want to use methods/objects associated with a window object, the easiest way is to obtain a reference to an appropriate window
object. For some/many things it is possible to do so without obtaining such a reference, but it is usually easier to just get a reference to the most recent browser window.
如果浏览器窗口存在(在某些情况下,您可以在不存在浏览器窗口的情况下运行,例如在启动时),您可以获得对最新浏览器window
的引用,document
和 gBrowser
带有:
If a browser window exists (in some instances you could be running where no browser window exists, yet, e.g. at start-up), you can obtain a reference to the most recent browser window
, document
, and gBrowser
with:
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
对象可用是许多人遇到的问题.
The lack of having the global window
object available is something that many people encounter as a problem.
参考文献:
这篇关于Firefox 附加组件 window.navigator.userAgent 错误:窗口未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!