otsukare Thoughts after a day of work

How To Detect WebGL

I have spoken at the wonderful ParisWeb 2011 conference about the issue Web browsers had because of bad Web development practices. People seemed to be surprised that could happen for big brand Web sites. Today, I got another example of hardcoded user agent sniffing.

Nokia is just releasing Nokia Maps 3D WebGL (beta). Cool! When you go there with a browser which doesn't support WebGL, you are welcomed with the following message: "This 3D experience requires the latest version of Google Chrome." Note. It doesn't say "This 3D experience requires a browser supporting WebGL." It sounds fishy. Let's see.

Map of Nokia here in WebGL

There is a javascript script for WebGL detection. The script contains a check function.

var check = function() {
    var Public = {};
    var supportedBrowsers = {"Chrome": 9,
                             "Firefox": 8};

My forefront is full of bruises and prints of the keyboard. Why? Just Why? It's even harder to understand when a little bit below in the code, there is the proper way to detect the WebGL context.

var contextNames = ["webgl","experimental-webgl","moz-webgl","webkit-3d"];
for(var i = 0; i < contextNames.length; i++){
            try{
                gl = canvas.getContext(contextNames[i]);
                if(gl){
                  break;
                }
            }catch(e){
                noWebGL("Unfortunately, there's a WebGL compatibility problem. </br> You may want to check your system settings.");
                return;
            }
            if(gl === undefined) {
                noWebGL("Unfortunately, there's a WebGL compatibility problem.  </br>You may want to check your system settings.");
                return;
            }
        }

Oh wait! Luz Caballero has recently written an article on dev.opera.com about Opera, Chrome, Safari and Firefox support of… WebGL.

and, and, and (thanks Mike Taylor), you can do something ala Sencha

//Feature test WebGL
  (function() {
    try {
      var canvas = document.createElement('canvas');
      PhiloGL.hasWebGL = function() {
          return !!(window.WebGLRenderingContext && (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
      };
    } catch(e) {
      PhiloGL.hasWebGL = function() {
          return false;
      };
    }
  })();

When I say that each time someone does user agent sniffing a Web page dies, I'm not kidding.