Monday, April 2, 2012

Check for local file browsing with JavaScript

Because I do most of my research while commuting by train, I often pull entire websites offline using httrack. While browsing the jQuery Mobile documentation locally this morning, I stumbled upon following gem.

I was curious to see how they determine whether a page is browsed locally or not. Looking into the source, I was a bit dissapointed to find nothing but plain common sense. The trick is comparing the protocol of the current location with known local protocols.
if ( location.protocol.substr(0,4)  === 'file' ||
     location.protocol.substr(0,11) === '*-extension' ||
     location.protocol.substr(0,6)  === 'widget' ) {
    // Disable AJAX support etc
If you would want to use that check in multiple locations in your codebase, you might want to extend the location object with an isLocal function.
window.location.constructor.prototype.isLocal = function() { 
    return this.protocol.substr(0,4)  === 'file' || 
            this.protocol.substr(0,11) === '*-extension' || 
            this.protocol.substr(0,6)  === 'widget'; 
The function could be used like this.
if (window.location.isLocal()) {
    // Disable AJAX support etc


  1. Hi This is great info. But can you please tell about how to disable this. I have created a game which after being published is checking whether it is running locally through this mode. How do i disable this. I removed this script but the file index.html is running in mozilla but not in chrome.

    Do you have an idea of why this is happening

    1. I don't understand your question. What is it you want to disable?