title: WKWebView: localStorage becomes null on window.close
body: <p>I have some 3rd-party content in a WKWebView that tries to read from localStorage on window-close. WKWebView doesn't trigger any events on window.close, so I'm doing it myself in the <code>webViewDidClose</code> delegate method.</p>
  
  <p>The problem is that as soon as <code>window.close()</code> is executed, localStorage becomes null! This does not happen in a desktop browser window. Interestingly, only localStorage is lost, sessionStorage remains accessible.</p>
  
  <p>In Safari inspector console:</p>
  
  <pre><code>onunload=function() {
      debugger;
      // localStorage is null
      // sessionStorage is Storage
  }
  close();
  </code></pre>
  
  <p>On the native side:</p>
  
  <pre><code>func webViewDidClose(_ webView: WKWebView) {
      // Trigger the unload event before closing the web view
      webView.evaluateJavaScript("dispatchEvent(new Event('unload'));")
  
      // Give the content some time to respond to the event, and then destroy the web view
      DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
          self.webView?.removeFromSuperview();
          self.webView = nil
      }
  }
  </code></pre>