How to detect if a web page is running from a website or local file system

switch(window.location.protocol) {
   case 'http:':
   case 'https:':
     //remote file over http or https
     break;
   case 'file:':
     //local file
     break;
   default: 
     //some other protocol
}

I used a slightly modifed version compared to @Beejor that also handles a possible port. It allows setting a base uriHost for e. g. ajax/jquery requests that may need the host portion if running as local file instead of running via SSH tunnel or directly via IP:Port. The detection portion is in the if-else conditions.

var uriHost = "";
if (window.location.protocol === "file:") {
  console.log("Running as local file!");
  // like: file://<path>/index.html
  uriHost = "http://<my-host-or-ip>:<my-port>";
} else if (
  !window.location.host.replace(/(localhost|127\.0\.0\.1)(:\d+)?/i, "")
) {
  console.log("Running on local server (ssh tunnel etc.)");
  // like: "http://127.0.0.1:<my-port>"
} else {
  console.log("Running normally, via web server");
  // like: "http://<my-host-or-ip>:<my-port>"
}
// now do something with uriHost, e.g. for ajax uris etc.

To check if running as local file (i.e. file://) only checking window.location.protocol === "file:" should be enough.


For testing different 'kinds' of local, all at once:

// Returns the page location type
// 0 (falsey) = Local file, direct from disk (file://path/to/file.html)
// 1 (truthy) = Virtually remote file, from local server (http://localhost)
// 2 (truthy) = Remote file from remote server (http://example.com)

function locationType(){
    if( window.location.protocol == 'file:' ){ return 0; }
    if( !window.location.host.replace( /localhost|127\.0\.0\.1/i, '' ) ){ return 2; }
    return 1;
}

Rationale: you may want to test for whether the page is a) on a remote server, or b) on a local server (same computer, for testing, like with AMP), or c) a local file, retrieved directly from disk via the "file://" protocol.

Note that this doesn't handle every possible edge case. For example, you can technically redirect different IPs to "localhost", and other non-"file://" schemes (like "foo://") may in fact represent local access. But it works for most cases and can be otherwise tweaked as needed

Testing only for "http" and "https" is a bit limited, since there are dozens of other LAN and WAN network schemes in use around the world. Whether or not they're local or can even use HTML/JS code may vary, of course (IANA URI Schemes).

Tags:

Javascript