ID:53727
 
The past two days I've been straining to figure out a way to detect a difference between Chrome's V8 and Safari's JavaScriptCore.

Unfortunately, V8 appears to be a carbon copy of JavaScriptCore with JIT compilation, making it extremely difficult to detect. The internet was no help, with everybody using either navigator.userAgent or navigator.vendor.

Why shouldn't you use such things? Here's just an example:

http://www.lifehacker.com.au/tips/2009/01/30/ google_chrome_accesses_hotmail_by_pretending_its_safari-2.ht ml

Websites often block certain browsers because they don't want to deal with cross-browser compatibility, so browsers will often spoof the userAgent/etc. to appear as another browser. userAgents are also subject to spyware which can severely corrupt them.

So after many headaches, I finally found a subtle difference between the two browsers that can be used for browser detection:

if (window.devicePixelRatio)  //If WebKit browser
{
if (escape(navigator.javaEnabled.toString()) == 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D')
{
alert('Chrome');
}
else if (escape(navigator.javaEnabled.toString()) != 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D')
{
alert('Safari');
}
}


This works by the fact that Function.toString() in Safari preserves whitespace while Chrome's does not. This is not likely to change unless Google considers it a bug; I'm thinking they did it on purpose, and I don't see Safari changing their ways.
I don't know Javascript (anything beyond the very basics, at least, though I pretty much forgot those!), but this looks like an interesting find. Good job.
Interesting find, I wondered why Hotmail didn't work for me.

Chrome forever! :D
Wouldn't this be easier to do with something like Perl or PHP?
Servers read the user agent to determine the browser, just like JavaScript.