title: SwiftUI: WKWebView with a delegate to watch URL and close when it reaches a point + open a certain link in new URL
body: <p>I have been hunting everywhere for a solution to my problem, and for some reason I am struggling to find any good resources on creating WebViews in SwiftUI and customizing / setting delegates for it. I am working with a 3rd party API that requires me to open a WebView, the user logs into something, and when that's done (signal comes via reaching a certain URL), the sheet should close. At the same time, if a certain click is taken, a <em>new</em> tab would open up, but my WebView is blocking that so no action occurs. These types of links should open in Safari.</p>
  <p>I have defined a very simple WebView: UIViewRepresentable already:</p>
  <pre><code>struct WebView: UIViewRepresentable {
  
      var url: URL
  
      func makeUIView(context: Context) -&gt; WKWebView {
          return WKWebView()
      }
  
      func updateUIView(_ webView: WKWebView, context: Context) {
          let request = URLRequest(url: url)
          webView.load(request)
      }
  }
  </code></pre>
  <p>And it is called as such (note this is an example):</p>
  <pre><code>                        Button {
                              showModal.toggle()
                          } label: {
                              Text(&quot;**Check ESPN**&quot;)
                          }
                          .sheet(isPresented: $showModal
                                 , onDismiss: {}
                                 , content: {
                                  WebView(url: URL(string: &quot;https://www.espn.com&quot;)!)
                              }
                          )
  </code></pre>
  <p>I have found this StackOverflow question that appears to have the delegate I need to open a link in Safari when it attempts to open a new tab. <a href="https://stackoverflow.com/questions/30603671/open-a-wkwebview-target-blank-link-in-safari/30604481#30604481">Open a WKWebview target=&quot;_blank&quot; link in Safari</a></p>
  <p>On top of this, I need a delegate to watch the URL and when the url contains &quot;done&quot;, then the sheet should close.</p>
  <p>Where in the world do I put that delegate definition? How do I assign it as a delegate for my <code>struct WebView</code>? Do I need to call my WebView in a different way within my sheet once I add the delegate?</p>