JavaScript’s window.location

By on  

Need current browser location information?  Keep in mind that the JavaScript's window.location object gives you all of that information about the window's current location.

Javascript Window Properties for:

window.location = {
	hash: '#myAnchor',
	host: 'davidwalsh.name',
	hostname: 'davidwalsh.name',
	href: 'http://davidwalsh.name:80/article.php?s=david+walsh+blog#myAnchor',
	pathname: '/article.php',
	port: '80',
	protocol: 'http:',
	search: '?s=david+walsh+blog',
	replace: 'function replace() { [native code] }',
	assign: 'function assign() { [native code] }',
	reload: 'function reload() { [native code] }'

Javascript Redirect

How can this be used? One example is doing a JavaScript redirect:

window.location = 'http://davidwalsh.name'; //redirects to homepage

Or you could use it to compare link hrefs to find out if a link is external or internal. Or you could build a sweet history manager!

Track.js Error Reporting

Recent Features

  • 5 More HTML5 APIs You Didnât Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

  • Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • Editable Content Using MooTools 1.2, PHP, and MySQL

    Everybody and their aerobics instructor wants to be able to edit their own website these days. And why wouldn't they? I mean, they have a $500 budget, no HTML/CSS experience, and extraordinary expectations. Enough ranting though. Having a website that allows for...

  • CSS Rounded Corners

    The ability to create rounded corners with CSS opens the possibility of subtle design improvements without the need to include images.  CSS rounded corners thus save us time in creating images and requests to the server.  Today, rounded corners with CSS are supported by all of...


  1. Well, you have to remember that there are two different locations. The location that the document was loaded from (window.location), and the location that relative paths to new documents are suppose to be loaded from (the base location). Usually they’re the same.

    Let’s say that your site is running through a proxy host because of security, performance or some other reason. In that case the proxy may insert a tag (or header) to refer the relative links in the document to the original host.

    In that case it may be preferable to have the plugins use the base location for reference. Unfortunately the tag may contain a relative URI. So we have to parse it compared to the window.location. Fortunately the URI class in MooTools-More does this for you. new URI() defaults to the base location.

  2. Bonus: window.location.replace(“myurl.com”) replaces the current page in history with “myurl.com”. That way, the back button does not go back to a page to be redirected again.

  3. @Sebastian Markbåge: As always, I enjoy your take!

    @Eric Wendelin: Thank you for the bonus round! :)

  4. The window object has so many attrs that i’ve never used.
    Great article.

  5. It seems so simple, but I can’t get an onClick to take me to a new page while it sets a cookie.

    var newMeal = document.getElementsByName('groceries'); 
    var expires = new Date(); 
    expires.setTime (expires.getTime() + 24 * 60 * 60 * 1000);
    var expiryDate = expires.toGMTString();
    function newCookie(add,newMeal) {
     document.cookie = add + "=" + newMeal + "; expires=" + expiryDate;
    function toShoppingList() {
        window.location = "http://www.whatsfordinner.net/Testing-Insert-div.html"

    This is a meal page.

    Shopping list for a new meal

  6. David,

    Please disregard my previous message. The problem must be with the cookie because when I took that out, my redirect worked perfectly. I’m attempting to move information from one page to another page and am not sure how to best accomplish this. Well, back to the drawing board!

    If you have a minute to look at the two pages (one for sending and one for receiving), I would value any suggestions you can offer.





  7. If you would like more examples of this and a live example view http://tundrablue.com/development/JavaScript/WindowLocation.html

  8. Jenny Lu


    I was wondering if you can use javascript to automatically scroll to a certain part of the page.

    forexample, if i just type in http://www.blahblah.com and it will automatically scroll to a certain part of the page.

  9. Thanks for sharing David. We use that technique to allow people to move between web & mobile sites without automatically redirecting them back to the mobile site all the time.

  10. Ferand

    I have a frustratng problem. The asp code I am working on no longer recognises replace as a valid method under widow.location. That is , when window.location.replace appears then no green or red lines appear and nothing shows up on the errors page.

    However, when I try running the code the application now acst as though the line was not there. The page that it tries to access does exist.

    A key issue is that window.location will no longer recognise replace as a valid method under location – when I try to type in something after the location. bit it does not show up on the list that appears. I can type in something like rhubarb with no differemce, a red or green line still does not appear.

    The script definition that it appears under is . The type bit used to be missing, but taking it out now doesnot make a difference,

    Any hints?

  11. Ferand

    Further to this –

    I’m not sure why I’m missing that bit of code in my final paragraph. it’s a script tag with the langage and type correctly dfined.

    Also, I forgot to say, other cited methods such as reload are also missing from the location object. I now seem to have an loaction object lacking in some critical methods, and the cause is unclear. Internet research indicates that they should be there.

  12. Ferand

    Further to this still, none of the methods (assign, reload , replace) appear.

    Nor do any of the standard properties (href, host, hostname, port, protocol, search, hash)

    What I am getting on the list I mentioned before are such curious things as boolean, alert, ActiveXObject, catch , Date & else. None of these seem to apply to location and URLs (which is what location is concerned with) at all. It only seems to look for items on the asp form to use as methods or properties, instead of what it’s supposed to be looking for.

    Maybe I have a bad target schema issue. I’m currently runnng on IE7. What would a right one be.

  13. Ferand

    Further to this still – sorry I keep making new discoveries – whenever I choose window, then press dot I get a list of standard Window properties and methods, including location, plus extras such as boolean and Date. So Window.location is not a problem.

    The problem settles in when I try to access any location properties or methods. None , including the overlooked pathname property from above, appear.

    Instead I get the window object’s properties, methods, extras etc appearing again. I could thus use the builder to type window.location.location.location etc etc without Visual Studio complaining at all.

    It may be a doctype or a target schema issue. But what is a more precise cause and how can it be fixed?

  14. Ferand

    It’s OK, it was a target schema issue. Once I’d used the HTML 4.01 target schema and not the default HTML 1.1 target schema, my worries went away. That’s all it took , apparently.

    The problem with the location properties as described above were still there, but were apparently one big red herring.

    I’m not satisfied that I fully understand all this, but the lesson here seems to be, if something like window.location.replace is not working, try another target schema in Visual Studio.

  15. Wil Moore III

    Real world scenario:

    You are writing an HTML5 application which is running on an embedded platform (television, set top box, etc); the application listens for server events and at some point, receives a notification that it should load a newer version of itself.

    I’ve found that window.location.replace is what you want in this particular case. It would be bad form to upgrade a client just to allow them to navigate back to the previous version by clicking the back button :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Serve a Directory via Python

    Sometimes I'm working with a test HTML file and some JavaScript but need to work off of a served space.  In that case, I sometimes need to swap out folders within MAMP Stack which leads to a maintenance nightmare.  Bleh. I recently found out that you can...

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...