简体   繁体   English

当用户关闭选项卡时,我运行什么 JavaScript 代码?

[英]What JavaScript code do I run when the user closes the tab?

Summarize the problem总结问题

I'm trying to create a macOS tabbed web browser using WKWebView and Swift.我正在尝试使用 WKWebView 和 Swift 创建一个 macOS 选项卡式 web 浏览器。 Everything works fine except the webpage doesn't know I closed the tab.一切正常,除了网页不知道我关闭了标签。 I want to tell the webpage that I closed the tab我想告诉网页我关闭了标签

Describe what you've tried描述你尝试过的东西

I haven't tried anything because I don't know what to do我没有尝试过任何事情,因为我不知道该怎么做

Show some code显示一些代码

I've tried doing this我试过这样做

webView.removeFromSuperView()

But the webpage didn't know that I closed the tab但是网页不知道我关闭了标签


I don't know much javascript so please include code instead of explaining我不太了解 javascript 所以请包含代码而不是解释

Javascript scripts use onbeforeunload and onunload events to tap into browser closing. Javascript 脚本使用onbeforeunloadonunload事件来触发浏览器关闭。

Since you know the browser is about to close, you can dispatch this event yourself.由于您知道浏览器即将关闭,您可以自己调度此事件。 For example, with beforeunload event:例如,使用beforeunload事件:

let script = """
   const event = new Event("beforeunload", { cancellable: true });
   const cancelled = !window.dispatch(event);
   // return back whether the user cancelled
   cancelled;
"""

When you need to close the browser, invoke the script:当您需要关闭浏览器时,调用脚本:

let webView = WKWebView()
// ... other config
webView.evaluateJavaScript(script, completionHandler: { result, error in
   guard let cancelled = result else { return }
  
   if cancelled == 1 {
     // ... do whatever
   }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM