WWDC Quick Look 💓 By SwiftGGTeam
Discover WKWebView enhancements

Discover WKWebView enhancements

Watch original video

Highlight

Apple has added content world isolation, callAsyncJavaScript, page scaling, PDF/WebArchive export, ITP enabled by default, and App-bound domains to WKWebView in iOS 14 and macOS Big Sur, allowing apps to more safely embed web content into native experiences.

Core Content

Many apps will put a website into theUIWebView. The page can be displayed and the business can run, but once the App wants to control scrolling, splice multiple sites, listen to page events, or export content, the boundaries of the old WebView begin to blur. Web scripts and App injection scripts share the same JavaScript world, variables may overwrite each other, and malicious pages may also encounter states that the App does not want to be exposed.

This session uses a fictional Browser Pets App to connect these questions. It will combine two internal websites into one news flow. The app will be responsible for native navigation, search, sharing and security policies, and the web page will continue to be responsible for existing content. Migrate toWKWebViewFinally, developers gain a set of capabilities to incorporate web content into native app management.

Apple’s changes are divided into five categories. The first type is isolation: when the page’s own JavaScript is turned off, the App can still run its own scripts;WKContentWorldYou can also put App Script into a separate JavaScript world. The second category is bridging:callAsyncJavaScriptand with replypostMessageLess string and message tracking code to write between native code and modern asynchronous JavaScript. The third category is rendering:pageZoomAnd custom media types allow apps to inject less CSS when adjusting web page performance. The fourth category is export: search, PDF, WebArchive and macOS printing complete common document capabilities. The fifth category is privacy: ITP is enabled by default, and App-bound domains use whitelists to limit sites with deep interactions.

Detailed Content

1. Press navigation to close the page JavaScript

(05:58) The old practice is toWKPreferencesofjavaScriptEnabledset tofalse. The problem is that many App interactions in WKWebView are also completed by executing JavaScript. Introduced in iOS 14 and macOS Big SurWKWebPagePreferences.allowsContentJavaScript, it only turns off the scripts that come with the web page content, and the App-side JavaScript is still available.

API: WKWebPagePreferences.allowsContentJavaScript
Scope: per-navigation web page preferences
Disables: inline scripts, remote JavaScript files, JavaScript URLs
Keeps: JavaScript evaluated by the app
Use case: disable a feed page's custom scrolling script while keeping app logic active

Key points:

  • WKWebPagePreferencesThe scope of scope is one navigation, suitable for determining script strategy by page.
  • allowsContentJavaScriptFor the web content itself, the script interaction between App and WKWebView will not be cut off.
  • The example in the session is to use JavaScript to customize scrolling on the news flow page, and the native scrolling experience will be restored after the App closes it.
  • This capability is suitable for scenarios where the App controls the presentation layer and the web page only provides content.

2. Use WKContentWorld to isolate App scripts

(09:03) The second problem encountered with Browser Pets is naming conflicts. There is in the webpagecommentDetailsFunction, the script injected by the App also uses the same symbol, and as a result, the comment area of ​​the web page becomes blank.WKContentWorldProvides a standalone JavaScript sandbox. The page world represents the script of the web page itself, and the client world represents the script of the App.

Problem: page JavaScript and app JavaScript both define commentDetails
API: WKContentWorld
Page world: web content's own JavaScript state
Client world: app JavaScript state
Adoption path: run evaluateJavaScript calls in the default client world
Also supported: install WKScriptMessageHandler in a specific content world

Key points:

  • WKContentWorldWhat is isolated is the JavaScript global object, and the page script cannot see the state set by the App script.
  • App scripts can still call the DOM API and modify the DOM.
  • evaluateJavaScriptYou can specify the default client world to avoid conflict with the page’s own symbols.
  • WKScriptMessageHandlerIt can also be installed into a specified content world to isolate the message entry together.

3. Less string spelling and call asynchronous JavaScript directly

(11:43) oldevaluateJavaScriptA common way to write this is to spell the parameters into a new JavaScript string. When the parameters come from native dictionaries or numbers, they must be serialized manually.callAsyncJavaScriptAllows reuse of a fixed piece of JavaScript and passing values ​​using named parameters.

API: callAsyncJavaScript
Input style: constant JavaScript string plus named arguments
Automatic bridge: Cocoa string -> JavaScript string
Automatic bridge: number -> JavaScript number
Automatic bridge: Cocoa dictionary -> JavaScript object
Return rule: JavaScript must explicitly return a value
Promise rule: if the return value is a Promise, completion waits until it resolves

Key points:

  • JavaScript strings no longer need to be re-concatenated for each set of parameters.
  • The API is responsible for serialization and deserialization of parameter types, reducing manual conversion between numbers, strings, and dictionaries.
  • completion handler is only available if explicitreturnOnly then do we get meaningful values.
  • returnPromise, the completion handler will wait for promise fulfillment, which makesfetchThis type of asynchronous Web API is easier to receive native code.

4. Let postMessage come with its own reply channel

14:18WKScriptMessageHandlerOriginally it was more like a one-way street. After JavaScript sends a message, if the native side wants to reply, it must maintain the message id, callback table and race condition handling. In iOS 14 and macOS Big Sur, JavaScriptpostMessagereturnPromise, the new handler form will receive the completion handler.

JavaScript side: postMessage returns a Promise
Native side: WKScriptMessageHandler receives a completion handler
Reply path: native code calls the completion handler
JavaScript result: the Promise returned by postMessage resolves

Key points:

  • message reply no longer requires developers to hand-write a set of ID and callback tracking mechanisms.
  • Calling the completion handler on the native side is the timing of promise resolution on the JavaScript side.
  • This is suitable for scenarios where page events need to wait for the judgment result on the App side, such as comment notifications, permission checks, and content selection.

5. Rendering, searching and exporting WKWebView API

(16:56) Browser Pets wants to upscale old web pages to modern iPhone screens. Inject CSSzoomIt can be done, but it will compete with the page style for control, and may also create a race condition in navigation.WKWebView.pageZoomTurn the full page zoom into a property of WebView itself.

(18:39) Another example is hiding the original header and footer of the web page. Mac WebView was previously able to render itself as a certain media type, and WKWebView brings this capability to all platforms in 2020. After the App sets a custom media type, the existing CSS media query on the web page can be switched to App-specific display.

(19:43) The content layer capabilities have also increased. WKWebView provides platform-consistent page lookup with configurable orientation, case sensitivity, and wrapping; results are selected and scrolled into view when found. In terms of export,createPDFComplete off-screen content can be saved as a searchable PDF,createWebArchiveDataThe current DOM and sub-resources can be saved to facilitate later debugging and testing.

Rendering: WKWebView.pageZoom
Rendering: custom media type on WKWebView
Find: built-in WKWebView find functionality
Export: createPDF with default or custom configuration
Export: createWebArchiveData for DOM plus sub-resources
Load archive: load(data, mimeType)
Mac addition: WKWebView printing on macOS Big Sur

Key points:

  • pageZoomWhat solves the problem of full page scaling is that there is no need to inject CSS after each navigation.
  • Custom media type allows the web page to adapt to the App container using CSS, which is suitable for existing sites to retain multiple presentations.
  • The built-in find function follows the search habits of AppKit and UIKit, and is suitable for long articles, comments, and document pages.
  • createPDFFor sharing and archiving, it can include content outside the current screen.
  • createWebArchiveDataFor debugging, testing, and pasteboard scenarios, a snapshot of the web content is saved.

6. Enable ITP by default and use App-bound domains to limit deep interactions

(25:15) Intelligent Tracking Prevention (ITP) works by default on all WKWebView Apps starting with iOS 14 and macOS Big Sur. For universal browser apps, users can still close it just like Safari to deal with compatibility issues.

(26:46) App-bound domains are used to describe which domain names are part of the core implementation of the App. Browser Pets only whitelists WebKittens and Pups on Safari. Other comment links can still be loaded, but the App and introduced frameworks cannot interact deeply with these sites. This is in line with the least privilege principle.

Default privacy: ITP enabled for all WKWebView apps
Configuration key: WKAppBoundDomains in Info.plist
Value: array of domains that are core to the app
Outside domains: loading still works
Outside domains: deep interaction is blocked
Strict mode: add WKAppBoundDomains with an empty array

Key points:

  • ITP is the default privacy protection and does not require the app to actively open it.
  • WKAppBoundDomainswritten inInfo.plist, a collection of sites that express App trust and deep interaction.
  • Pages outside the whitelist can still be opened, but cannot be deeply read or manipulated by the app.
  • If the App loads any webpage but does not need to interact with the webpage content, you can use an empty array to turn off in-depth interaction for all domain names.

Core Takeaways

  • Make a secure multi-site information flow: put content from several own websites into the same native feed. Why it’s worth doing:WKContentWorldallowsContentJavaScriptAnd App-bound domains can manage App scripts, page scripts, and whitelisted external links separately. How to start: Configure the core site firstWKAppBoundDomains, and then move the App injection script to the default client world.

  • Make a built-in web page problem recurrence package: Add an “Export current web status” entry to the beta version of the app. Why it’s worth doing:createWebArchiveDataIt can save the current DOM and sub-resources, which is more suitable for reproducing page structure problems than screenshots. How to start: Call WebArchive export in the debug menu to save the data to disk or load it into another WKWebView for comparison.

  • Make a native document search and sharing experience: Add search and PDF sharing to the help center, agreement page or long comment page. Why it’s worth doing: WKWebView’s find function selects and scrolls to the results,createPDFAbility to export complete content off-screen. How to start: Put a search button and a share button on the native navigation bar to trigger the find process and PDF generation process respectively.

  • Make a low-script content reading container: Turn off remote page scripts for information, announcements, and article pages, and only retain the App’s own scripting capabilities. Why it’s worth doing:allowsContentJavaScriptCustom scrolling, ad scripts, or uncontrolled interactions can be removed from the page without cutting off essential controls from the app. How to start: Set by URL in navigation policy delegateWKWebPagePreferences

  • Make an App-specific display layer for the old site: Hide the existing web page header/footer in the App and enlarge it to a suitable size. Why it’s worth doing:pageZoomand custom media types can reduce race conditions and side effects of injected CSS. How to start: First use Web Inspector to find out if the page already has media query or CSS class, and then put the zoom and media type in the WKWebView configuration layer.

  • What’s new in Web Inspector — In this session, I used Web Inspector many times to troubleshoot page problems in WKWebView. 10646 You can continue to learn about the 2020 debugging tool updates.
  • What’s new for web developers — 10188 Finally, it is recommended to continue looking at Web-facing features, 10663 covering Web API, CSS, media and JavaScript updates for Safari and WebKit.
  • Meet Face ID and Touch ID for the web — Both belong to Safari & Web, and bring the Web Authentication API to the Safari website login process.
  • Build trust through better privacy — 10188 ITP and App-bound domains are privacy boundary designs, 10676 further explaining Apple’s privacy principles and platform capabilities.

Comments

GitHub Issues · utterances