我想获得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
?
答案 0 :(得分:1)
Firefox附加组件通常在未定义全局window
对象的范围内运行(如果已定义,则取决于当前运行的代码部分是如何输入的)。如果要使用与窗口对象关联的方法/对象,最简单的方法是获取对适当的window
对象的引用。对于某些/很多事情,可以在没有获得这样的引用的情况下这样做,但通常更容易获得对最新浏览器窗口的引用。
如果存在浏览器窗口(在某些情况下,您可以在没有浏览器窗口的情况下运行,例如在启动时),您可以获得对最新浏览器window
的引用,{{1 }和document
与:
gBrowser
缺乏可用的全局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;
}
对象是很多人遇到的问题。
参考文献: