DEV Community

Filip Němeček
Filip Němeček

Posted on

Dynamically modify page in WKWebView in iOS

If you have page in WKWebView in your app, you can modify it pretty freely. This can be useful for example when you are embedding your own page and want to provide different look/functionality when loaded in a web view.

WKWebView has method evaluateJavaScript which does exactly what it says. It will run any JavaScript code you provide on the loaded page.
This can be also very useful for getting information back about the page. For example you can ask for the total height and modify your app user interface accordingly.

Method looks like this:

func evaluateJavaScript(_ javaScriptString: String, 
      completionHandler: ((Any?, Error?) -> Void)? = nil)
Enter fullscreen mode Exit fullscreen mode

completionHandler is not required but you can check for errors to verify everything works or use the Any? to get result from JS code.

webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { (height, error) in
         if let height = height as? CGFloat {
        } 
})
Enter fullscreen mode Exit fullscreen mode

Yet another use case can be filling forms on pages with saved data so users have better experience and don’t have to do it manually. Since you can run any JavaScript the possibilities are pretty endless. If you are sure there is jQuery loaded on the page, you can use it to simplify some common tasks.

I would highly recommend writing your JavaScript in editor that supports it so you don’t miss ; or something like that when running the code in WKWebView. Also it is a good idea to test the code on the page in browser by opening the developer console and pasting it here. It is much faster to debug than running your app and doing it via evaluateJavaScript method.

Is anything not clear? Do you want more information? Ask in the comments and I will do my best to help you. Thanks for reading!

Top comments (0)