0

Here is what I'm trying to do:

  • when the user signs up I store the current window in a variable and I send him an email:

    <script>sessionStorage.setItem("window", window)</script> <?php sendEmail(/*...*/); ?>

  • when the user opens the email, I get the previously saved window from the storage and close it

    <script>sessionStorage.getItem("window").close()<script>

This would prevent the browser from having too much unuseful windows opened on the same domain.

The problem is that I get an error like this:

Uncaught TypeError: sessionStorage.getItem(...).close is not a function

(same result if I previously store it on variable)


Furthermore, when I log the current window I get an object containing every method:

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
alert: ƒ alert()
...

when I log the stored function I just get this:

[object Window]

Is there a way to achieve my goal?

Is it possible to pass a window as a simple variable?

Am I doing something wrong?

1 Answers1

0

This is happening because sessionStorage does not store objects but strings. What you need to do to add an object to the storage is to stringify it when writing and parsing it when reading:

sessionStorage.setItem('test', JSON.stringify({ value: 'this is a test' }))
JSON.parse(sessionStorage.getItem('test'))

While this will work most objects, window sadly enough is not one of them because it contains circular references (ie: it references itself) You can read more about that problem here: Stringify DOMWindow object

Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41
  • I tried with this: `sessionStorage.setItem(\"window\", JSON.stringify({ value: window }))` but it does not work... [this](https://stackoverflow.com/a/6012438/13327421) answer says that it it impossible to stringify a window... Could it be the case? –  May 11 '20 at 22:44
  • Did your script open the window in the first place? If not then you cannot close it using javascript. If you use a service worker then you can reclaim all the windows open on your domain using that. – miknik May 11 '20 at 22:52
  • @miknik I've not opened the window with javascript, but I thought that since I'm passing the variable from the window itself I could close it... –  May 12 '20 at 06:10
  • Nope, sorry. See the [docs](https://developer.mozilla.org/en-US/docs/Web/API/Window/close) – miknik May 12 '20 at 07:16
  • @miknik a workaround like opening a new tab and closing the current one? or is it better to give up? –  May 12 '20 at 13:27