iOS 14: What is new for WKWebView

nemecek_f

Filip Němeček

Posted on July 3, 2020

iOS 14: What is new for WKWebView

In this post let's go over some of the interesting changes for WKWebView in iOS 14.

Sandboxing for JavaScript

There is new WKContentWorld type to represent the separation of website's JavaScript and JavaScript that developers inject into the page. They can now run in completely separate environments.

That means mainly that you don't have to worry about accidentally interacting with some website JS code and vice versa. So no naming clashes and also protections from malicious websites that may try to influence the app via JS communication.

There are two content worlds defined and these are page for the website environment and defaultClient which should be the first choice when injecting JS into the page.

WKContentWorld is a new parameter in methods like evaluateJavaScript or callAsyncJavaScript which we look at later in this post. This also applies to the WKUserContentController which allows you to send data from JavaScript to your app. This can now be associated with content world. So for example you have multiple instances and each within its own content world to prevent interference.

Better JavaScript evaluation with callAsyncJavaScript

This new method will likely be the most used way for running JS code in WKWebView. Mainly for two reasons. You can pass arguments parameter which is a [String: Any] dictionary and will be mapped to JS types. So you don't have to include those in the JavaScript string and can reuse it with different arguments.

What does the "async" in the method name means? It is an indication that this method can handle JS promises which are one of the option how JS handles asynchronous code. If your JS code returns promise then the completionHandler of this method will not be called immediately and somehow return this promise but it will wait and you will get the value. This means callAsyncJavaScript can be trivially used with fetch to download any kind of data and then access it in Swift code.

findString

As the name implies this method will let us find text in a webpage. You can do a bit of configuration or just use defaults that should work pretty well. The result is then selected and WKWebView automatically scrolls so the result is visible.

Create PDF from page

Since iOS 11 we can take a snapshot of currently visible part of the page with the createPDF page which also lets us to configure the result we want.

pageZoom

We can now easily zoom pages with this new property so we don't have rely on JavaScript to change the CSS to control zoom.

This was just a sort of high-level overview. For more watch the Discover WKWebView enhancements session.

Note: Not all the new stuff is available in Xcode 12 Beta 1.

💖 💪 🙅 🚩
nemecek_f
Filip Němeček

Posted on July 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related