I'm trying to understand when window.close()
will / won't work. I know there are some requirements around the window being script closeable etc., but it seems like there are some additional requirements that I can't find formally laid out (at least, not laid out in terms I can't understand with my current javascript knowledge.)
At a high level, my use case is as follows:
- a user clicks a button
- I do some stuff and then do something like
windowRef = window.open("http://example.com/somedocument.pdf","popup")
. - Once the user takes clicks a different button, I want to be able to call
windowRef.close()
and have it close the pdf I opened in a popup.
My current implementation works as long as the url I'm opening shares a domain with the window that's trying to close it, and not otherwise. That's fine (I can guarantee the PDF will come from the same domain as the window trying to close it) but I'd like to understand why this doesn't work for URLs with different domains (and if there are other cases where it won't work that I haven't run into yet).
Based on some experimenting in my application / the browser console, it seems like window.close()
will work if the url I'm opening shares a domain with the window I'm trying to close it from, but not otherwise. That's purely based on testing / guessing though, I haven't found documentation explaining why this might be the case.
I've read the MDN documentation for window.close, but I can't seem to find it documented when exactly this function will work, and when it will just return "undefined" (but not log an error like "Scripts may not close windows that were not opened by script.)
I thought this might have to do with the Same-origin policy, but that article calls out window.close()
as not having the same-origin requirement, and some tests I ran seem to confirm this.
Can someone explain to me what needs to be true for me to be confident that, if I'm opening a pdf in a popup window using window.open()
to send a window to a URL to the pdf, I can later close that popup with window.close()
Comments
Post a Comment