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.
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.
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.
switch(window.location.protocol) { case 'http:': case 'https:': //remote file over http or https break; case 'file:': //local file break; default: //some other protocol }
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With