Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I'm a newbie to javascript. How can I detect if my javascript is being run from a web site (http://) vs a local file.

like image 406
dan gibson Avatar asked Oct 13 '10 04:10

dan gibson


People also ask

Can browser read local files?

Web browsers (and JavaScript) can only access local files with user permission. To standardize the file access from the browser, the W3C published the HTML5 File API in 2014. It defines how to access and upload local files with file objects in web applications.

Can JavaScript access local files?

JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.


2 Answers

switch(window.location.protocol) {    case 'http:':    case 'https:':      //remote file over http or https      break;    case 'file:':      //local file      break;    default:       //some other protocol } 
like image 64
Jacob Relkin Avatar answered Sep 21 '22 09:09

Jacob Relkin


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).

like image 31
Beejor Avatar answered Sep 21 '22 09:09

Beejor