Get URL with JavaScript

At some point in time you need to get the current URL and do some logic based on it. JavaScript has handy API called window.location which has all the information related to the windows current location.

Running console.log(window.location); in the console or your JavaScript file will return the following Location object:


Location {
    origin: "http://website.com", 
    host: "website.com",
    hostname: "website.com",
    href: "http://website.com/",
    origin: "http://website.com",
    pathname: "/",
    port: "",
    protocol: "http:",
    search: ""
    assign: function,
    ancestorOrigins:    DOMStringList, 
    reload: function reload() { [native code] },
    replace: function () { [native code] },
    toString: function toString() { [native code] },
    valueOf: function valueOf() { [native code] }
}

Having a reference to the location you are now able to start tinkering away. Here a couple of examples.

Getting values from URL

var pathname = window.location.pathname;
console.log(pathname);

Manipulating URL


window.location.search = 'super awesome values';

Redirecting URL

var newURL = "https://s12621.p20.sites.pressdns.com";
window.location = newURL;

One gotcha with the above snipper is make sure you add the protocol. e.g. http://.

Reloading

In the event that you need to reload the current page you can also call window.location.reload.


window.location.reload(true);

Hopefully the above gives you enough of an insight into working with the current URL to get your out of trouble.

Want to become a better web developer?

Join over 25,000 other developer & designers who get awesome links to the best news and articles each week delivered directly to their inbox.

This post currently has no responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *