Search code examples
javascriptswiftwkwebview

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. 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


Solution

  • Javascript scripts use onbeforeunload and onunload events to tap into browser closing.

    Since you know the browser is about to close, you can dispatch this event yourself. For example, with beforeunload event:

    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
       }
    })