JavaScript: Get URL (window.location)

By Xah Lee. Date: . Last updated: .

This page shows you how to get the current URL.

The window.location object contains URL info. You can use it like this:

console.log(window.location.href);

The window.location object has the following properties. Their values are string.

href
Entire URL. Example: http://example.com/4960/p?tn=1&wvr=5
. If you set window.location.href, browser will load it.
protocol
Protocol. Example: http://, ftp://, file://
host
The host name and port number (if the URL has port number). Example: www.example.com:8080
hostname
Host name. Example: www.example.com
origin
Origin. Example: http://www.example.com
port
Port number. Example: 8080
pathname
Pathname, with beginning slash. Example: /js/js_get_url.html
search
Part of URL after ?, including ?. Example: ?topnav=1&wvr=5 [see Update URL Param]
hash
The part of url after #, including #. Example: #hoot

See also: Encode URL, Escape String

Naming of URL Parts

Here is a visual review about URL parts.

http://www.example.com:80/a/b/c?x=1&y=2#frag

http
protocol
www.example.com
host. The “example.com” is domain name. “www” is sub-domain.
80
port number
a/b/c
resource path
x=1&y=2
query string. A list of key/value pairs, separated by &
frag
Url fragment

JavaScript/DOM, Get/Set URL

BUY
ΣJS
JavaScript in Depth

DOM Scripting

Overview

DOM Methods

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc