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!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • Create a Simple News Scroller Using MooTools, Part I:  The Basics

    News scroller have been around forever on the internet. Why? Because they're usually classy and effective. Over the next few weeks, we'll be taking a simple scroller and making it into a flexible, portable class. We have to crawl before we...

  • Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...


  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

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...