Detecting browsers javascript hacks in a tweet
15 Feb 2009Hi folks.
I am recently very fond of the term "code in a tweet" which means that a very useful piece of source code can even fit a Twitter post. Below here is the shortest javascript that can detect IE browser by Andrea (yeah, IE sucks and we have to detect it to eliminate its problems)
[sourcecode language="jscript"]
IE='\v'=='v'
[/sourcecode]
Moreover, Gareth Heyes has come up with other browser detections and gather them together
[sourcecode language="jscript"]
//Firefox detector 2/3 by DoctorDan
FF=/a/[-1]=='a'
[/sourcecode]
[sourcecode language="jscript"]
//Firefox 3
FF3=(function x(){})[-5]=='x'
[/sourcecode]
[sourcecode language="jscript"]
//Firefox 2
FF2=(function x(){})[-6]=='x'
[/sourcecode]
[sourcecode language="jscript"]
//IE detector I posted previously
IE='\v'=='v'
[/sourcecode]
[sourcecode language="jscript"]
//Safari detector
Saf=/a/.__proto__=='//'
[/sourcecode]
[sourcecode language="jscript"]
//Chrome
Chr=/source/.test((/a/.toString+''))
[/sourcecode]
[sourcecode language="jscript"]
//Opera
Op=/^function \(/.test([].sort)
[/sourcecode]
Usage: The variable assignment is the abbreviation of the browser e.g. FF, IE, Op, Saf, Chr which return true or false.
And this is the most interesting part: one-liner to rule them all
[sourcecode language="jscript"]
B=(function x(){})[-5]=='x'?'FF3':(function x(){})[-6]=='x'?'FF2':/a/[-1]=='a'?'FF':'\v'=='v'?'IE':/a/.__proto__=='//'?'Saf':/s/.test(/a/.toString)?'Chr':/^function \(/.test([].sort)?'Op':'Unknown'
[/sourcecode]
Usage: B will return a string of the abbreviation of the browser
Tell me what do you think? And if you find any cool stuff like that let me know.