315

What's the difference between window.location and document.location? Should both of them reference the same object?

ruakh
  • 175,680
  • 26
  • 273
  • 307
Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230
  • 3
    For a use case showing their difference, see http://stackoverflow.com/a/12098898/632951 – Pacerier Oct 11 '14 at 17:01
  • A good read can also be found here: https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-location-interface Especially the warning given ("The Location exotic object is defined through a mishmash of IDL, invocation of JavaScript internal methods post-creation, and overridden JavaScript internal methods. Coupled with its scary security policy, please take extra care while implementing this excrescence.") is note-worthy IMHO. – Elmar Zander Dec 10 '22 at 11:54

18 Answers18

288

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/html/browsers.html#dom-location

sam
  • 40,318
  • 2
  • 41
  • 37
rahul
  • 184,426
  • 49
  • 232
  • 263
  • 14
    Downvoted. Answer contradictory. It boldly says they are same, then describes the differences in lighter text. They are decidedly not same. – danorton Feb 07 '12 at 01:47
  • 55
    C'mon trigger-happy down-voters, lighten up a bit. For the most part, they behave similarly CONSIDERING THE CAVEAT SPECIFIED by rahul. Let's not nail him on semantics. A little philadelphia, gentlemen. I, for one, found his answer fully satisfying. +1 (Christoph's should be the accepted answer, but rahul's is acceptable -- at the least, not worthy of down-vote.) – cssyphus Nov 20 '12 at 18:03
  • 11
    -1 for recommending a best practice (always using `window.location`) without providing any justification for it. If you won't provide the justification, why should anyone take your advice? Christoph's answer is far more useful in this regard. – Mark Amery Aug 06 '14 at 23:20
  • +1 but also see the answers by Phil Hamer and Christoph below, they add essential background info and caveats to fully understand the issue. – jrz Oct 31 '14 at 19:12
240

The canonical way to get the current location object is window.location (see this MSDN page from 1996 and the W3C draft from 2006).

Compare this to document.location, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location was replaced with document.URL (see here on MSDN), which is also part of DOM Level 1.

As far as I know, all modern browsers map document.location to window.location, but I still prefer window.location as that's what I've used since I wrote my first DHTML.

Christoph
  • 164,997
  • 36
  • 182
  • 240
  • 2
    if you use `window.location` , isnt it equally valid to just use `location` ? – commonpike Mar 01 '16 at 09:46
  • 10
    @commonpike It is -- in the context of a script in [at least] a HTML document, the global object where all defined variables become properties, is the `window` object. Thus, any variable or function you define at the top level of your script, is a property of the object referenced by `window`, which happens to be the global object. Global object is implied when absent like `window.` -- thus `location` is interpreted to be `window.location`. Caveats -- f.e. `if(an_undefined_variable)` will throw an error if variable wasn't defined -- `if(window.an_undefined_variable)` won't. – Armen Michaeli Jun 28 '16 at 18:43
  • @commonpike, yes, so long as you are in a standards-compliant browser environment and there isn't a different variable `location` in a local scope. – Paul Draper May 15 '23 at 18:45
96

window.location is read/write on all compliant browsers.

document.location is read-only in Internet Explorer (at least), but read/write in Gecko-based browsers (Firefox, SeaMonkey).

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 13
    I can't reproduce the claim that `document.location` is read-only in IE. I can successfully assign to it in IE 10, 9, 8 and 6 (using VMs from http://modern.ie). – Mark Amery Aug 06 '14 at 23:10
49

document.location was originally a read-only property, although Gecko browsers allow you to assign to it as well. For cross-browser safety, use window.location instead.

Read more:

document.location

window.location

ABN
  • 1,024
  • 13
  • 26
xkeshav
  • 53,360
  • 44
  • 177
  • 245
39

Interestingly, if you have a frame, image, or form named 'location', then 'document.location' provides a reference to the frame window, image, or form, respectively, instead of the Location object. Apparently, this is because the document.forms, document.images, and window.frames collection name lookup gets priority over the mapping to window.location.

<img name='location' src='location.png'>

if (document.location.tagName == 'IMG') alert('Hello!')
Nathan
  • 8,093
  • 8
  • 50
  • 76
Phil Hamer
  • 391
  • 3
  • 3
  • 2
    There is no priority, it is simply overwritten – Pacerier May 25 '13 at 06:07
  • 10
    No, it's not overwritten. It's shadowed, so Phil is right about element taking precedence during property resolution. – kangax Sep 22 '13 at 18:06
  • @kangax, Seems like you are right: http://jsfiddle.net/uL4ysszr/ . But how reliable is this behavior? Is it sufficiently cross-browser? – Pacerier Oct 11 '14 at 16:41
  • I think it's pretty cross-browser, unfortunately. Don't have time to check but IIRC you should be able to find this behavior spec'd in HTML5. – kangax Oct 14 '14 at 13:59
  • 1
    Just tested this (October 2016). It appears that `window.location` and `document.location` cannot be shadowed in Chrome or Firefox. – Mr. Llama Oct 26 '16 at 18:27
  • 1
    @Mr.Llama You are right. It appears all modern browsers no longer behave in the way I described above. It seems to be due to giving document.location the "Unforgeable" attribute. Relevant Chromium change: https://src.chromium.org/viewvc/blink?view=revision&revision=189862 And Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1133760 – Phil Hamer Feb 14 '19 at 19:14
28

As far as I know, Both are same. For cross browser safety you can use window.location rather than document.location.

All modern browsers map document.location to window.location, but I still prefer window.location as that's what I've used since I wrote my first web page. it is more consistent.

you can also see document.location === window.location returns true, which clarifies that both are same.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
talha2k
  • 24,937
  • 4
  • 62
  • 81
15

document.location === window.location returns true

also

document.location.constructor === window.location.constructor is true

Note: Just tested on , Firefox 3.6, Opera 10 and IE6

YOU
  • 120,166
  • 34
  • 186
  • 219
  • 1
    @Pacerier Why? For objects, `===` and `==` are equivalent. – Mark Amery Aug 06 '14 at 23:21
  • 6
    @MarkAmery, That's wrong and can be easily demonstrated: `"abc" == new String("abc")` returns `true` while `"abc" === new String("abc")` returns `false`. – Pacerier Aug 07 '14 at 18:33
  • 9
    @Pacerier Okay, let me state that slightly more rigorously and less ambiguously: when comparing *two objects* with each other (rather than just an object with anything), `==` and `===` are equivalent. See [the spec](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf) sections 11.9.3 and 11.9.6. For non-null, non-undefined, non-number, non-bool, non-string values with the same type, `==` behavior is governed by 11.9.3 part 1f, and `===` behavior by 11.9.6 part 7, which identically read *Return `true` if x and y refer to the same object. Otherwise, return `false`.* – Mark Amery Aug 07 '14 at 18:58
  • 16
    @MarkAmery, There is no guarantee that both `document.location` and `window.location` are pointing to objects. You are missing the whole point of triple equals; using 2 equals **does not prove** that they are the same obj. **We should use 3 equals and not 2 equals because 2 equals will give us a false positive.** On a browser whereby document.location is a URL string equal to `window.location.toString()`, Then `document.location==window.location` will return true while `document.location===window.location` will return false. – Pacerier Oct 11 '14 at 17:16
  • 1
    @Pacerier Aha - I get it at last. You are quite correct, at least as far as the `document.location === window.location` comparison goes. The fact that the `.constructor` comparison is thrown in too means, I think, that this answer is still sound, but using `===` would simplify the reasoning. – Mark Amery Oct 11 '14 at 17:32
  • 1
    @MarkAmery, It will still fail and give false positives on a browser that allows overriding of `.constructor` property of a `String` or `Number` or `Boolean` instance. In short, YOU's code *may* work, but it's definitely not cross browser, and therefore it doesn't **prove** what it's supposed to prove. – Pacerier Oct 11 '14 at 18:05
  • when it comes to testing you need to stick with the same one? – Nikos Mar 10 '23 at 10:33
12

Yes, they are the same. It's one of the many historical quirks in the browser JS API. Try doing:

window.location === document.location
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
9

window.location is the more reliably consistent of the two, considering older browsers.

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
4

It's rare to see the difference nowadays because html 5 don't support framesets anymore. But back at the time we have frameset, document.location would redirect only the frame in which code is being executed, and window.location would redirect the entire page.

Marquinho Peli
  • 4,795
  • 4
  • 24
  • 22
3

At least in IE, it has a little difference on local file:

document.URL will return "file://C:\projects\abc\a.html"

but window.location.href will return "file:///C:/projects/abc/a.html"

One is back slash, one is forward slash.

Justin
  • 1,050
  • 11
  • 26
3

Well yea, they are the same, but....!

window.location is not working on some Internet Explorer browsers.

divHelper11
  • 2,090
  • 3
  • 22
  • 37
2

I would say window.location is the more reliable way of getting the current URL. Following is the difference between the window.location and document.url that came in front in one of the scenarios where I was appending hash parameters in the URL and reading it later.

After adding hash parameters in the URL.

In an older browser, I was not able to get the hash parameters from the URL by using document.url, but when I used window.location then I was able to get the hash parameters from the URL.

So it's always better to use window.location.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
azhar_salati
  • 1,554
  • 5
  • 28
  • 54
  • 2
    -1. The question didn't even mention `document.URL` - it was about `window.location` and `document.location`. Also, `document.url` doesn't exist = it should be uppercase. – Mark Amery Aug 06 '14 at 23:24
2

I prefer using document.location, even though location, document.location, and window.location returns same object.

Reasons for using document.location are:

  1. Browser compatibility section of window.location mentions

Before Firefox 57, single quotes contained in URLs were escaped when accessed via URL APIs. See bug 1386683.

  1. Browser compatibility section of document.location mentions

Full support.

  1. Mdn location reference uses document.location in their examples.

    // location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
    const loc = document.location;
    console.log(loc.href);      // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
    console.log(loc.protocol);  // https:
    console.log(loc.host);      // developer.mozilla.org:8080
    console.log(loc.hostname);  // developer.mozilla.org
    console.log(loc.port);      // 8080
    console.log(loc.pathname);  // /en-US/search
    console.log(loc.search);    // ?q=URL
    console.log(loc.hash);      // #search-results-close-container
    console.log(loc.origin);    // https://developer.mozilla.org:8080
    
    location.assign('http://another.site') // load another page
    
ABN
  • 1,024
  • 13
  • 26
2

tl;dr They are virtually always the same. Prefer window.location.

The Document object's location getter steps are to return this's relevant global object's Location object, if this is fully active, and null otherwise.

The Window object's location getter steps are to return this's Location object.

https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location

When are they different? If the document is not fully active. For example:

const iframe = document.createElement("iframe");
document.body.append(iframe);
const { contentDocument, contentWindow } = iframe;
iframe.remove();
contentWindow.location; // not null
contentDocument.location // null
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
2

document.location.constructor === window.location.constructor is true.

It's because it's exactly the same object as you can see from document.location===window.location.

So there's no need to compare the constructor or any other property.

Pacerier
  • 86,231
  • 106
  • 366
  • 634
Gene Karasev
  • 21
  • 1
  • 1
1

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

Kainax
  • 1,431
  • 19
  • 29
  • 2
    I didn't downvote, however, it could be because this is a really old question and your answer doesn't provide any new or valuable evidence that one is better than the other. Or, it could be because your answer suggests the opposite of the public opinion, regardless of the merit you give to what Google has done historically. Or, it could be that the downvoter just didn't like how you put emphasis on parts of your answer that don't really need emphasizing. Could be anything really. That's the beauty of anonymous voting on SO. – M.Babcock May 19 '17 at 19:51
  • Could be because *Google* doesn't prefer anything. One of the devs *at* Google wrote that code and it hopefully got reviewed by another dev or more. – DylanYoung Jun 03 '22 at 03:14
1

Actually I notice a difference in chrome between both , For example if you want to do a navigation to a sandboxed frame from a child frame then you can do this just with document.location but not with window.location

M.Abulsoud
  • 989
  • 7
  • 23