Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  118] [ 1]  / answers: 1 / hits: 24335  / 11 Years ago, mon, september 23, 2013, 12:00:00

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.


More From » browser

 Answers
9

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.


[#75501] Sunday, September 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daytonm

Total Points: 519
Total Questions: 83
Total Answers: 89

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;