Get a Page URL with JavaScript

September 28th, 2010 - Posted by Steve Marks to Javascript / jQuery, Web Development.

Sometimes it’s necessary to perform actions based on the user’s current URL, and the page that they are viewing. If doing this dynamically after the page has loaded then JavaScript provides a method to get the current website address, and more.

Firstly, lets look at a very simple example below:

<input type="button" value="Click Here" onclick="alert(window.location.href);">

And now lets look at it in action:

Hopefully, when you click the button above you should see a popup alert containing the website address. This should match the URL in your browsers address bar.

Easy huh? But that’s not all…

As you’ll know there are multiple parts to a website address (the query string, the filename, the domain name etc). Above we used the ‘href’ property to get the full website address, but what if you only want a certain part of the URL? Luckily there are a few different properties we can use to get the bit we need. A full list of these properties can be found at the following URL:

This entry was posted on Tuesday, September 28th, 2010 at 7:03 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first