4.4 In browsers, globalThis does not point directly to the global object

In browsers, globalThis does not point directly to the global, there is an indirection. As an example, consider an iframe on a web page:

  • Whenever the src of the iframe changes, it gets a new global object.
  • However, globalThis always has the same value. That value can be checked from outside the iframe, as demonstrated below (inspired by an example in the globalThis proposal).

File parent.html:

  1. <iframe src="iframe.html?first"></iframe>
  2. <script>
  3. const iframe = document.querySelector('iframe');
  4. const icw = iframe.contentWindow; // `globalThis` of iframe
  5. iframe.onload = () => {
  6. // Access properties of global object of iframe
  7. const firstGlobalThis = icw.globalThis;
  8. const firstArray = icw.Array;
  9. console.log(icw.iframeName); // 'first'
  10. iframe.onload = () => {
  11. const secondGlobalThis = icw.globalThis;
  12. const secondArray = icw.Array;
  13. // The global object is different
  14. console.log(icw.iframeName); // 'second'
  15. console.log(secondArray === firstArray); // false
  16. // But globalThis is still the same
  17. console.log(firstGlobalThis === secondGlobalThis); // true
  18. };
  19. iframe.src = 'iframe.html?second';
  20. };
  21. </script>

File iframe.html:

  1. <script>
  2. globalThis.iframeName = location.search.slice(1);
  3. </script>

How do browsers ensure that globalThis doesn’t change in this scenario? They internally distinguish two objects:

  • Window is the global object. It changes whenever the location changes.
  • WindowProxy is an object that forwards all accesses to the current Window. This object never changes.

In browsers, globalThis refers to the WindowProxy; everywhere else, it directly refers to the global object.