在javascript中嘲笑一个useragent? [英] Mocking a useragent in javascript?

查看:159
本文介绍了在javascript中嘲笑一个useragent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种以编程方式动态更改navigator.userAgent的方法。在我尝试获得自动javascript单元测试器失败的尝试中,我放弃并试图开始使用fireunit。我立即猛烈闯入使用实际浏览器进行javascript测试的墙壁之一。

I'm looking for a way to programmatically change navigator.userAgent on the fly. In my failed attempt to get an automated javascript unit tester, I gave up and attempted to begin using fireunit. Immediately, I've slammed into one of the walls of using an actual browser for javascript testing.

具体来说,我需要更改navigator.userAgent来模拟几百个userAgent字符串,以确保在给定的功能上正确检测和覆盖。 navigator.userAgent只读,所以我好像卡住了!我怎么能模拟navigator.userAgent?用户代理切换器(插件)可以切换FF的useragent,但是我可以在javascript中执行吗?

Specifically, I need to change navigator.userAgent to simulate a few hundred userAgent strings to ensure proper detection and coverage on a given function. navigator.userAgent is readonly, so I seem stuck! How can I mock navigator.userAgent? User Agent Switcher (plugin) can switch FF's useragent, but can I do it within javascript?

推荐答案

尝试:

navigator.__defineGetter__('userAgent', function(){
    return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'

在FF2和FF3中尝试过。

Tried it in FF2 and FF3.

这篇关于在javascript中嘲笑一个useragent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆