Bridge Native IOS and Javascript code in WKWebView

Gunjan
1 min readNov 8, 2019

--

Recently I was working a prototype where I had to render a webview in an IOS app. Also the webview had to be work in offline load so we would have to package it with the IOS workspace.

Rendering the webview was pretty easy . Basically I had to create a standard View and then use the following code ..

import WebKitclass DetailViewController: UIViewController {@IBOutlet weak var webView: WKWebView!override func viewDidLoad() {super.viewDidLoad()webView.navigationDelegate = selfself.setToolBar()let bundle = Bundle.mainlet filename = “index”let fileExtension = “html”let directory = “graphing”let indexUrl = bundle.url(forResource: filename, withExtension: fileExtension, subdirectory: directory)let indexPath = bundle.path(forResource: filename, ofType: fileExtension, inDirectory: directory)let webUrl = bundle.url(forResource: directory, withExtension: nil)//Load the file in the webview
webView.loadFileURL(indexUrl!, allowingReadAccessTo: webUrl!)
}

The next step was to call a javascript function and get a response back . There are many different ways to trigger the function . That really depends on your requirement. It could be in the View Load itself or you can imagine this being triggered by a native button being tapped.

Here is how you call a javascript function and get a return value from the javascript function.

webView.evaluateJavaScript(“window.mywebview.myJavascriptFunction()”, completionHandler: { (results, error) inprint(returnValue ?? “: returnValue”)})

Thats it !

There are several other ways you can work with WkWebViews and as I work on more I will update this blog , so check back again!

--

--

Gunjan
Gunjan

No responses yet