Determining whether JavaScript is running on a server or locally

This article can be read in about 2 minutes.
PR

The purpose 

This Javascript code checks whether it’s running on a server or locally. (This is used, for example, to run test code locally and production code on the server.)

PR

Check by Protocol

You can check this in the protocol part of the URL.

When running locally, the URL protocol will be “file:”, while on a server it will be “http:” or “https:”.

Therefore, you can check this using code like the following:

if (location.protocol == "file:") {
    //////local
} else {
    //////server
}
PR

Result

We are able to determine whether the JavaScript code was running on a server or locally and branch the processing accordingly.

comment

Copied title and URL