Ok this is an edge case I have managed to land in. I am testing my app on the new Tizen OS. My JS code has thousands of navigator checks. Something like:
navigator.userAgent.toLocaleLowerCase().indexOf("android") || navigator.userAgent.toLocaleLowerCase().indexOf("iPad")
Now Tizen OS's userAgent on my test device does not have either of those strings. A lot of my css and JS is breaking as a result. I am in the POC mode right now and do not want to spend time in adding an additional check to all those conditions. Is there a way to programmatically set userAgent ? Something along the lines of:
navigator.userAgent += " Tizen" //does not work.
MDN says its a read-write property. I am not able to modify it though. Help me with this. Either another smart way to spoof userAgent or the correct way to set this. Thanks.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With