ariya.io About Talks Articles

detecting browser sniffing

2 min read

The latest version of PhantomJS has added the support for initialization callback, which allows you to modify the global objects which will be seen by the client code. The example I previously shown was changing the behavior of Math.random to return a constant.

What follows is another example, available in the repository (look under examples/detectsniff.js), to create a fake navigator object so that you can detect if the code running on the web page tries to sniff your browser user agent. The most important piece is shown here:

page.onInitialized = function () {
    page.evaluate(function () {
        (function () {
            var userAgent = window.navigator.userAgent,
                platform = window.navigator.platform;
 
            window.navigator = {
                appCodeName: 'Mozilla',
                appName: 'Netscape',
                cookieEnabled: false,
                sniffed: false
            };
 
            window.navigator.__defineGetter__('userAgent', function () {
                window.navigator.sniffed = true;
                return userAgent;
            });
 
            window.navigator.__defineGetter__('platform', function () {
                window.navigator.sniffed = true;
                return platform;
            });
        })();
    });
};

Basically what we do is logging the access to both platform and userAgent property of the navigator object. Because there is no message passing support yet (see issue 224), we store the status in another property which will be retrieved later. This is not the most bulletproof workaround since the client code can circumvent that, but it will go away once issue 224 is solved.

Examples on how to use it:

phantomjs examples/detectsniff.js http://ariya.github.com/js/useragent/
Checking http://ariya.github.com/js/useragent/...
The page tried to sniff the user agent.

and

phantomjs examples/detectsniff.coffee http://m.bing.com
Checking http://m.bing.com...
The page did not try to sniff the user agent.

BTW, there is also the CoffeeScript version, find it in examples/detectsniff.coffee.

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook