javascript - 以编程方式关闭/退出 PWA

标签 javascript google-chrome progressive-web-apps

如何关闭/退出我的 PWA?

我曾假设我能够做到这一点:

window.close();

不幸的是,这会导致通常的错误:

Scripts may close only the windows that were opened by it.



有没有办法以编程方式关闭我的 PWA?

最佳答案

因此,请遵循 MDN 文档:

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.



关注 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


同样从第二部分开始,脚本将被视为不可关闭脚本( 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.



因此,恐怕在现代浏览器中,如果不控制谁打开它,就不可能真正关闭当前选项卡。这也适用于 iframe 打开的窗口。所有信息都在我链接的当前标准中,原因在我引用的那些中。几年前有使用 open("", "_self") 的变通方法和类似的解决方案,但我相信这个已经被修补了。

在 PWA 的情况下,只要浏览历史记录中没有推送事件,您将只能关闭应用程序(这意味着 window.history.length 在整个导航中保持为 1。在这种情况下,您的应用程序将被视为顶部只包含一个文档的级别浏览上下文,因此 window.close() 可以。可以测试最后一个确认:转到 twitter.com -> 安装 Twitter PWA -> 打开 PWA -> 打开控制台并写入 window.close() ,它将立即关闭窗口。在它导航到 PWA 内的任何链接的那一刻,历史只有一个文档的条件是不满足的。

额外尝试找出为什么这是一个安全问题:
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

关于javascript - 以编程方式关闭/退出 PWA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60583049/

相关文章:

javascript - 如何从 AngularJS Controller 调用自定义 Javascript 函数?

angular - 使用 Angular Service Worker 的 Android 本地通知

JavaScript:使用函数返回的对象,而不使用对象的对象

javascript - 为什么用函数调用替换 Javascript 内联函数会产生不同的行为?

javascript - 对象内部的函数

javascript - 我如何(真的!)使 JavaScript 异步调用同步(在 Chrome 上)?

css - 检查包含 kendo-ui 样式的页面中的元素时,Google Chrome Devtools 崩溃

jquery - 仅限 Chrome : Overlay divs on scroll with fixed position scrolling issue

progressive-web-apps - 是否可以在 PWA/可信网络事件应用程序中使用 Adsense?

javascript - 用谷歌的sw-precache搭建的service worker真的能做到networkFirst吗?