1

I'm creating a hybrid app and I'm trying to pass some data from the WebView to the native app.

The best method I can think of to accomplish this is to use URL variables, and then add a listener to the URL in Swift to get the new data.

I'm able to get the URL variable from the WebView when it first loads with this Swift code...

func webViewDidFinishLoad(_ webView: UIWebView) {

   print(getQueryStringParameter(url: (webView.request?.url?.absoluteString)!, param: "id"));

}
func getQueryStringParameter(url: String, param: String) -> String? {
    guard let url = URLComponents(string: url) else { return nil }
    return url.queryItems?.first(where: { $0.name == param })?.value
}


This works great, but I can't seem to find a WebView listener to detect when I add a new URL variable through JS at a later time after the page loads. Here is that JS...

window.history.replaceState(null, null, "?id=mydata");

Any ideas how to listen for that in Swift? Or is there a better way to pass data from a web view to a native app?

nachshon f
  • 3,540
  • 7
  • 35
  • 67
  • You can make your view controller the delegate of your WKWebView Navigation, implement the method `func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {`, check the navigation type and the request url – Leo Dabus Dec 17 '17 at 03:14
  • https://stackoverflow.com/a/36231713/2303865 – Leo Dabus Dec 17 '17 at 03:15

1 Answers1

0

You can accomplish what you are looking for this code.

You need to use WKWebView and implement the respective delegates.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("finish to load")
        if webView.url!.absoluteString.range(of: "ADD_STRING_TO_BE_CHECKED_HERE") != nil
        {
            print("Success")

            //DO WHAT YOU NEED HERE
        }
    }

Hope this helps...

Jobins John
  • 1,265
  • 23
  • 45