我想得到userAgent https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/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 附加组件通常运行在全局范围内window
对象未定义(是否定义取决于当前运行的代码部分的输入方式)。如果要使用与窗口对象关联的方法/对象,最简单的方法是获取对适当窗口对象的引用window
目的。对于某些/许多事情,可以在不获取此类引用的情况下执行此操作,但通常更容易获取对最新浏览器窗口的引用。
如果存在浏览器窗口(在某些情况下,您可能在不存在浏览器窗口的情况下运行,例如在启动时),您可以获得对最新浏览器的引用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
对象可用是许多人遇到的问题。
参考:
- SDK: 窗口/实用程序 https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/window_utils
- SDK: windows https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/windows
- nsIWindowMediator https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator
- 在 chrome 代码中使用 Windows https://developer.mozilla.org/en-US/docs/Working_with_windows_in_chrome_code
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)