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:
https://davidwalsh.name:80/article.php?s=david+walsh+blog#myAnchor

window.location = {
	hash: '#myAnchor',
	host: 'davidwalsh.name',
	hostname: 'davidwalsh.name',
	href: 'https://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 = 'https://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!

Recent Features

Incredible Demos

  • By
    FileReader API

    As broadband speed continues to get faster, the web continues to be more media-centric.  Sometimes that can be good (Netflix, other streaming services), sometimes that can be bad (wanting to read a news article but it has an accompanying useless video with it).  And every social service does...

  • By
    Create a Clearable TextBox with the Dojo Toolkit

    Usability is a key feature when creating user interfaces;  it's all in the details.  I was recently using my iPhone and it dawned on my how awesome the "x" icon is in its input elements.  No holding the delete key down.  No pressing it a...

Discussion

  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.

    http://www.whatsfordinner.net/Testing-Insert-div.html

    http://www.whatsfordinner.net/Testing-toShoppingList.html

    Thanks,

    Jean

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

  8. Jenny Lu

    hello,

    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!