W ramach naszej witryny stosujemy pliki cookies zgodnie z Polityką Cookie. Zasady przechowywania lub dostępu plików cookie możesz zmienić w swojej przeglądarce.



Geekowy blog o łamigłówkach, JavaScript i wszystkim, co ciekawe.

The shortest way to detect IE in JavaScript

Tech stuff - JavaScript -
napisał Jakub Caban

I've recently stumbled upon yet another way to find out we are using Internet Explorer in JavaScript. It's beauty is all about its simplicity.

But first of all, let me show you the code:

var IE = !+"v1";

You might ask "what the heck?" - and believe me I did so at first.

Now the explanation. First of all - how this line should be read? From the inside - v - is the escape sequence for something so called "vertical tabulator" and that was some ancient time ago (15 years?) used in ASCII. And so it is still specified for backwards compatibility reasons of course. So it should be treated as white-space character. As so - "v1" is a string containing white-space character and "1" character. So that - +"v1" should be the string converted to the number. This conversion in JavaScript tells to ignore any white-spaces at the beginning and then try to read number as long as we have digits (and "." sign if present). So that +"v1" is now integer 1. Operator ! translates 1 to true and than negates it, so we have false. OK - in theory we should get false every time in the IE variable now.

But what Microsoft thinks about it? As we know they never care about any standards - they simple doesn't treat v as "vertical tabulator", and so they doesn't treat it as white-space character. So that conversion to number of "v1" is conversion of string starting with non-white-space and non-digit character (and not "."), so the result is integer 0. Converted to bool false, and than negated gives us true.

It's indeed simple and effective way of detecting IE via JavaScript. Surely it's better way than parsing Browser data string (actually than one should never be used), and simpler than conditional code.

The only question remains - what IE9 thinks about it? I don't have the answer yet, and probably we should wait for the release with such tests. But even if "v" thing will get fixed - hey! they yell IE9 will be standard compliant! If so, I'd rather have it not-detected in my code specially hacked for IEs.

O JavaScripcie i jego dzikich meandrach, do których tylko najwytrwalsi tubylcy zapuszczają się. I to nigdy bez odzieży ochronnej i dzidy z trzema końcami.

Podobne artykuły: