1

In the question, Persist variables between page loads, the accepted answer says that the data stored in window are retained.

It says,

The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.

When I tried writing to window object from chrome dev console and when navigated to some other page on the same domain, the values weren't retained.

This is what I did:

  1. Open https://stackoverflow.com/unanswered
  2. Open dev console and set window.testKey = "test-value"
  3. Navigate to a different page by clicking one of the questions link.
  4. Entering window.testKey in console returns undefined.

Also, a simple case of setting a value on window followed by a page refresh also doesn't seem to retain the value.

What am I missing?

Thiyagu
  • 17,362
  • 5
  • 42
  • 79

1 Answers1

1

The part you quote:

The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.

Is only about window.name, which is a special property, and this still works - to some degree - in current browsers.

Window.name:

Modern browsers will reset Window.name to an empty string if a tab loads a page from a different domain, and restore the name if the original page is reloaded (e.g. by selecting the "back" button). This prevents an untrusted page from accessing any information that the previous page might have stored in the property (potentially the new page might also modify such data, which might then be read by the original page if it was reloaded).

I the end it was just a hack and you should not rely on its functionality. For the same domain, you have localStorage or sessionStorage

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • Thank you. I missed the point that it is a special property. However, it doesn't seem to reset `window.name` when I go to a different domain as quoted – Thiyagu Oct 29 '21 at 07:56
  • @user7 How `window.name` behaves depends on the browser (and version). It could persist through different domains, and it could also be reset. You should assume that it will reset in the future for all browsers. – t.niese Oct 29 '21 at 07:58