What is window.origin?

14,794

Solution 1

WindowOrWorkerGlobal.origin returns the origin of the environment, Location.origin returns the origin of the URL of the environment.

Unfortunately Stack-Snippets null-origined frames will make for a confusing example...

At the risk of paraphrasing the specs themselves, let's say we are on https://example.com and from there, we create a new <iframe> element without an src attribute:

var frame = document.createElement("iframe")
frame.onload = function() {
  var frameWin = frame.contentWindow;
  console.log(frameWin.location.href); // "about:blank"
  console.log(frameWin.location.origin) // "null"
  console.log(frameWin.origin) // "https://example.com"
}
document.body.appendChild(frame);

Live example

The location of our frameWin is "about:blank" and its location.origin is "null", because "about:blank" is an opaque origin.

However, the frame's Window frameWin got its own origin set to the one of the parent Window ("https://example.com") which was set when frameWin's browsing context got initialized.


If you wish a little diving into the specs here are the relevant steps for the previous example:

If the element has no src attribute specified, or its value is the empty string, let url be the URL "about:blank".

If invocationOrigin is not null, and url is about:blank, then return invocationOrigin.

So here it has been determined that origin of the new browsing context is invocationOrigin, i.e the origin of the browsing context that did create frame, while url, used by location, is "about:blank".


Now the case of StackSnippets sandboxed frames is a bit particular in that they do have an src and thus a tuple-origin url, but since their sandbox attribute makes their origin opaque, they'll behave at the inverse of what is exposed in the previous example, making self.origin return "null" and location return the iframe's src's URL.

Solution 2

Quite an interesting question! 😊

We can start with some investigation - let's see the output from window

console.log(window)

That file is quite big... The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window and describes several features common to the Window and WorkerGlobalScope.

more details here

But then you want to see a very particular property window.origin.

window.origin That one is quite boring for stack overflow (code snippet) as you saw, the json obj returned for window brings:

"origin": "null"

This response is the way the window tell us that the origin is not the same and that we were not allowed the same-origin for that window. Quite common effect for iframe as you deducted yourself!

You also saw that the window.location is less boring... as it contains some more data to it as the Location interface represents the location (URL) of the object it is linked to and the cool thing is that any changes done on it are reflected on the object it relates to. So that is why we don't get a null in here.

window.location...

"location": {
    "ancestorOrigins": {
        "0": "https://stackoverflow.com",
        "length": 1,
        "item": function item() {
            [native code
            ]
        },
        "contains": function contains() {
            [native code
            ]
        }
    },
    "origin": "https://stacksnippets.net",
    ...
}

Solution 3

I think it's not documented because both are the same with little difference, It most cases it doesn't really matter which option you choose to use. There are, however, a few instances where one is preferred over the other, such as:

  1. same-origin policy conflicts if setting a new URL in an iframe or another window that is already of a different origin from the current window (e.g an iframe has a different domain than the document it is loaded in and you want to change the URL of the iframe) would use window. location to set the new URL. This is because location.href is read-only when called from a different origin (domain).
  2. if using use strictly in your JavaScript may cause an exception if using window. location since you are essentially assigning a string to an object, so here it would be best to use the full window.location.href.

See this question for reference.

Solution 4

Location describes the URL of the current page. It is available through the window. location property.

<a id='foo' href='#bar'>Go to #bar</a>


<div style='height: 1000px'></div>


<a id='bar' href='#foo'>Go to #foo</a>
<script>
  var printHash = function() {




    console.log("'" + window.location.hash + "'");

  };
  // Print initial hash
  printHash();
  window.onhashchange = printHash;
</script>`enter code here`

More info: Internet Explorer does not have access to window.location.origin, which is a bummer because it is a pretty handy variable to have, but we can make it work with a fairly straight forward check because we access .origin;

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
Share:
14,794

Related videos on Youtube

Snow
Author by

Snow

Updated on September 15, 2022

Comments

  • Snow
    Snow over 1 year

    What is window.origin? It doesn't seem to be documented in the usual place.

    It looks like it might be very similar to window.location.origin - for example, here on Stack Overflow, both return

    https://stackoverflow.com
    

    But inside an iframe, they're different:

    console.log(window.location.origin);
    console.log(window.origin);
    https://stacksnippets.net
    null
    

    The embedded snippet is inside an iframe without allow-same-origin. If you change the iframe, for example, if you edit Stack Overflow's HTML and manually add the attribute:

    <iframe name="313b857b-943a-7ffd-4663-3d9060cf4cb6" sandbox="allow-same-origin allow-forms allow-modals allow-scripts" class="snippet-box-edit" frameborder="0" style="">
                                                                 ^^^^^^^^^^^^^^^^^^
    

    and then run the snippet, you get:

    https://stacksnippets.net
    https://stacksnippets.net
    

    The same sort of behavior is exhibited on other sites with <iframe>s.

    Google does not appear to have any authoritative links on the subject. Searching for the exact phrase + Javascript gives many results related to iframes and postMessage, but no precise description of what window.origin actually is.

    Calling postMessage from a child iframe appears to result in the parent window receiving a message with the origin property matching the window.origin of the child frame - without allow-same-origin, it's null, otherwise it looks like it's the same as the window.location.origin of the child.

    The above is what I think I've figured out from guessing-and-checking, but I'm nowhere near certain. I'd appreciate a confirmation/explanation, preferably with a link to an authoritative source.

    • mplungjan
      mplungjan about 5 years
    • Mukyuu
      Mukyuu about 5 years
    • Snow
      Snow about 5 years
      Oh wow, thanks. I didn't think to search for WindowOrWorkerGlobalScope.origin
    • mplungjan
      mplungjan about 5 years
      so I get 50 rep? ;)
    • Snow
      Snow about 5 years
      @mplungjan Sure! Relevant info looks to be here and here (see allow-same-origin on the same page for why it was affecting the iframe), a "unique opaque origin" -> 'null' is set under various conditions, otherwise a tuple origin (like window.location.origin) is assigned.
    • fabb
      fabb
      Note that in the top window context, window.origin will return undefined on older browsers like IE11, Edge 17 and Safari 10, while window.location.origin will return the correct origin. Newer browsers seem to support both.
  • Snow
    Snow about 5 years
    It is documented in the links in the comments - if you describe and reference the official specification that describes the behavior (see my comment - "unique opaque origin" is an important phrase), I'll award a bounty :)