问题
How can I close/exit my PWA?
I had assumed I'd be able to do this:
window.close();
Unfortunately, that results in the usual error:
Scripts may close only the windows that were opened by it.
Is there any way to programmatically close my PWA?
回答1:
So following MDN documentation on this:
window.close
In the past, when you called the window object's close() method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not. This is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open.
Following the living standard
If current is null or its is closing is true, then return. (Here is when the problem comes, as browsing context is null unless you opened a new document using the javascript context)
If all the following are true:
- current is script-closable
- the incumbent global object's browsing context is familiar with current
- the incumbent global object's browsing context is allowed to navigate current
Also from the second part the script is going to be considered non-script-closable (Here you have more info)
A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.
So I am afraid that in modern browsers is quite impossible to actually close the current tab without having control over who opened it. This also applies to windows opened by iframes. All the info is in the current standard that I linked and the reasons are among the ones I quoted. Back some years there were work arounds using open("", "_self")
and similar solutions, but I believe this one have been patched.
In case of PWA, you will be only able to close the application as long as there are no push events in the browse history (this means that window.history.length
remains 1 for the whole navigation. In that case your application will be considered a top-level browsing context with only one document, hence window.close()
will do. This last affirmation can be tested: Go to twitter.com -> Install Twitter PWA -> Open the PWA -> open console and write window.close()
, it will inmediately shut the window. In the moment it navigates into any link within the PWA, the condition of history having only one document is unmeet.
Extra trying to find why was this a security issue: https://security.stackexchange.com/questions/120116/security-feature-preventing-javascript-from-closing-the-window
https://security.stackexchange.com/questions/133744/why-do-browsers-disallow-script-closing-an-opener-window-yet-allow-changing-its
来源:https://stackoverflow.com/questions/60583049/close-exit-a-pwa-programmatically