The location
is an object that contains information about the URL of the currently loaded page.
For example, location.href
, is the full URL and location.hostname
is only the domain.
An example to view of properties of the location
object for an url.
Consider a URL like this:
http://search.example.com:8080/search?v=javascript#results
for (var i in location) { console.log(i + ' = "' + location[i] + '"'); }
There are also three methods that location provides—reload()
, assign()
and replace()
.
There are different ways to navigate to another page using location object properties and methods.
window.location.href = 'http://www.packtpub.com' location.href = 'http://www.packtpub.com' location = 'http://www.packtpub.com' location.assign('http://www.packtpub.com') location.replace('http://www.yahoo.com')
replace()
is almost the same as assign()
. The difference is that it doesn't create an entry in the browser's history list.
To reload a page you can use: location.reload()
You can use location.href
to point it to itself, like so.
window.location.href = window.location.href
location = location
Property | Description |
---|---|
hash | Sets or returns the anchor part (#) of a URL |
host | Sets or returns the hostname and port number of a URL |
hostname | Sets or returns the hostname of a URL |
href | Sets or returns the entire URL |
origin | Returns the protocol, hostname and port number of a URL |
pathname | Sets or returns the path name of a URL |
port | Sets or returns the port number of a URL |
protocol | Sets or returns the protocol of a URL |
search | Sets or returns the querystring part of a URL |
Method | Description |
---|---|
assign() | Loads a new document |
reload() | Reloads the current document |
replace() | Replaces the current document with a new one |