Tuesday, November 15, 2011

Adventures in browser detection

So, today, I came across an interesting issue. I am working on a total overhaul of my personal CMS, and part of that includes a custom WYSIWYG editor. The editing happens inside an iframe element, but in order to make it a seamless experience, I want the iframe to dynamically resize itself according to whatever the contents need for dimensions. Makes sense, right? Well, then I come across this little beauty:

In order for it to work right, I have to use the dimensions of the iframe's body element in Chrome. But I have to use the dimensions of the iframe's html element in Firefox. Talk about irritating. So now I have to distinguish between these two great browsers. I think to myself, "Oh, well, that shouldn't be too difficult." And I tried using navigator.product. No joy.

Turns out, Chrome sets navigator.product to Gecko, just like Firefox. Even though Chrome is NOT Gecko.

So I thought maybe appName. Chrome sets its navigator.appName to... "Netscape".

appCodeName? Chrome sets it to - you guessed it - "Mozilla".

So I was compelled to check the userAgent string. But because Chrome and many other browsers report their UA strings as "Mozilla/5.0..." I knew Mozilla was out. I thought about looking for Firefox, but there are plenty of other Gecko-based browsers. So I thought, maybe "Gecko."

But, oh, wait. Chrome reports, among other things, that it is "KHTML, like Gecko."

So I ended up having to check for "Gecko" and then make sure that it wasn't "like Gecko."

If you're interested, here's the code I used...

if(navigator.userAgent.match(/Gecko/i) && !navigator.userAgent.match(/like Gecko/i)){ // Must be dealing with Firefox, etc.

Just because life in webdev land can't be easy.