How to set navigator userAgent?

∥☆過路亽.° 提交于 2019-11-29 15:38:07
Spudley

My JS code has thousands of navigator checks

In that case it is your JS code that is at fault.

You've basically just discovered the ultimate reason why doing UA string detection is considered really bad practice.

In short, if your code looks as described, then you're doing something wrong. There are very few legitimate reasons for detecting the UA string, and none of those reasons apply to code running on the client itself.

And thousands of lines of this stuff in the browser???? That's can only be doing bad things to the performance of your site.

Is there a way to programmatically set userAgent? MDN says its a read-write property.

The userAgent string is a read-only value.

However, you can override the getter, so there are ways of making it writable. Ugly, but possible.

I'd really recommend avoiding doing this though.

Even without browser vendors deliberately changing their UA strings to break this kind of code (which they do), your task is fundamentally never-ending; you're going to have to keep revisiting this code every time a new device/browser/version is released, and your thousands of lines of code just will keep getting bigger and bigger.

Plus of course, it will be completely unreliable if a user modifies his browser's UA string.

Fix it now with a hack if you must, but be aware that this will keep eating more and more of your time. You really need to consider switching to a better coding practice such as feature detection instead of UA detection.

I recently created a gist to make readonly propertys writable (You can find an example to overwrite the navigator.userAgent). Like Spudley said, it is ugly and not recommended but I used it for unit tests to change user agents on the fly, so be careful.

Gist: https://gist.github.com/moehlone/bed7dd6cb38fc55bd640

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!