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 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

I tried with this: sessionStorage.setItem(\"window\", JSON.stringify({ value: window })) but it does not work... this answer says that it it impossible to stringify a window... Could it be the case?
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 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...
Nope, sorry. See the docs
@miknik a workaround like opening a new tab and closing the current one? or is it better to give up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.