← coderrocketfuel.com

Get The URL Origin (Server Name) Of A Web Page In JavaScript

The origin of a URL indicates where a document, HTTP request, or web page originated from. It doesn't include any path information, but only the server name.

How do you get the URL origin of a web page when programming with JavaScript?

JavaScript has a built-in way to get this information using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Using that interface, you can get the URL origin with this method:

window.location.origin

This method will return a USVString containing Unicode serialization of the origin of the current page's URL.

Here are some example returned values to expect:

// Page URL: https://coderrocketfuel.com
window.location.origin = "https://coderrocketfuel.com"

// Page URL: https://coderrocketfuel.com/courses
window.location.origin = "https://coderrocketfuel.com"

// Page URL: https://subdomain.coderrocketfuel.com
window.location.origin = "https://subdomain.coderrocketfuel.com"

To quickly test this, open the developer tools in your favorite browser and execute the window.location.origin method in the JavaScript console. The URL origin string should be logged to the console.

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!