---
name: swiftui-webkit
description: "Web content in SwiftUI with WebKit for SwiftUI: WebView, WebPage, observable page state, navigation policies, link interception, JavaScript calls, local HTML or data, custom URL schemes. Use when an iOS 26+ screen shows articles, detail pages, help centers, in-app docs or other embedded HTML, CSS and JavaScript, or when replacing a WKWebView wrapper. Not for OAuth or deep-link routing."
metadata:
  source: multi-agent-pipeline
---

# WebKit for SwiftUI

Starting with the 26 releases (iOS, iPadOS, macOS, visionOS), WebKit ships a SwiftUI
surface of its own: `WebView` draws web content and `WebPage` is the
observable model behind it. Everything below needs `import WebKit` and those
OS versions.

## Picking the container

| Situation | Use |
|---|---|
| Web content that belongs to the app, shown inside a SwiftUI screen | `WebView` with a `WebPage` |
| Sending the user to an outside site with Safari behaviour | `SFSafariViewController` |
| OAuth or any third-party sign-in | `ASWebAuthenticationSession` |
| Deployment target below iOS 26, or a capability only the old API has | a `WKWebView` fallback |

Apple's WWDC25 WebKit guidance points SwiftUI apps away from UIKit and AppKit
web view wrappers wherever the new API covers the need. Sign-in never runs in
an embedded web view.

## Showing a page

The shortest path renders a URL and lets SwiftUI state decide which one:

```swift
import SwiftUI
import WebKit

struct ReleaseNotesView: View {
    let address: URL

    var body: some View {
        WebView(url: address)
    }
}
```

As soon as you need to issue requests yourself, watch state, run
JavaScript or steer navigation, own a `WebPage` and pass it to
`WebView(page)`. Deciding this up front is cheaper than retrofitting it.

```swift
@Observable
@MainActor
final class GuideModel {
    let page = WebPage()

    func open(_ address: URL) async throws {
        let events = page.load(URLRequest(url: address))
        for try await _ in events { }
    }
}

struct GuideScreen: View {
    @State private var model = GuideModel()
    let start: URL

    var body: some View {
        WebView(model.page)
            .task { try? await model.open(start) }
    }
}
```

## Loading and observing

`WebPage` is an observable class isolated to the main actor. Its load
methods:

- `load(_ request: URLRequest)` and `load(_ url: URL?)`
- `load(html:baseURL:)` for a string of markup
- `load(_:mimeType:characterEncoding:baseURL:)` for raw `Data`; the encoding
  is a `String.Encoding` such as `.utf8`

Each returns an async sequence of navigation events that throws when the
navigation fails. Observable properties include `title` (a non-optional
`String`), `url`, `isLoading`, `estimatedProgress`, `backForwardList`,
`hasOnlySecureContent` and, from the SwiftUI overlay, `themeColor`.

```swift
struct ArticleReader: View {
    @State private var page = WebPage()
    let story: URL

    var body: some View {
        WebView(page)
            .navigationTitle(page.title.isEmpty ? "Article" : page.title)
            .overlay(alignment: .top) {
                if page.isLoading {
                    ProgressView(value: page.estimatedProgress)
                }
            }
            .task {
                do {
                    let events = page.load(story)
                    for try await _ in events { }
                } catch {
                    // show an inline error state
                }
            }
    }
}
```

To react to every navigation rather than sampling one property, iterate
`page.navigations` with `for try await`. The released SDK has no
`currentNavigationEvent` property; the event sequences are the way to follow
progress. Details are in [page loading notes](references/loading-and-observation.md).

## Navigation policy

A type conforming to `WebPage.NavigationDeciding` can permit, cancel or adjust
navigations by request or by response. Typical jobs:

- keep the app's own domains inside the web view,
- cancel links to other domains and hand them to `openURL`,
- catch callback URLs,
- adjust `WebPage.NavigationPreferences` for a request.

```swift
@MainActor
final class DomainGate: WebPage.NavigationDeciding {
    var leaving: URL?

    func decidePolicy(for step: WebPage.NavigationAction,
                      preferences prefs: inout WebPage.NavigationPreferences)
        async -> WKNavigationActionPolicy {
        guard let target = step.request.url, let host = target.host() else { return .allow }
        if host.hasSuffix("docs.example.org") { return .allow }
        leaving = target        // opened outside the app by the view
        return .cancel
    }
}
```

This skill covers navigation inside web content. Routing the app itself from
a deep link belongs to the `swiftui-navigation` skill.

## JavaScript

`callJavaScript(_:arguments:in:contentWorld:)` runs the string as the body of
an async JavaScript function, so the script uses `return`. The result comes
back as `Any?`; cast it to the Swift shape you expect straight away, and pass
values through `arguments` rather than building them into the script text.

```swift
let raw = try await page.callJavaScript(
    "return [...document.querySelectorAll(selector)].map(n => ({ id: n.id, text: n.textContent }))",
    arguments: ["selector": "h2"]
)
let headings = raw as? [[String: Any]] ?? []
```

`callJavaScript` is not a message channel from the page to the app. For
simple one-off signals, the page can navigate to a custom callback URL that
the navigation decider intercepts; that is a workaround, not a full
replacement for `WKScriptMessageHandler`. `WebPage.Configuration` does expose
a `userContentController` (a `WKUserContentController`) for apps that need
structured script messages. See
[policy and script notes](references/navigation-and-javascript.md).

## Local content and custom schemes

For bundled HTML, offline documentation or resources the app generates,
register a `URLSchemeHandler` on a `WebPage.Configuration`:

```swift
var setup = WebPage.Configuration()
if let scheme = URLScheme("manual") {
    setup.urlSchemeHandlers[scheme] = ManualFiles()
}
let page = WebPage(configuration: setup)
// later: page.load(URL(string: "manual://getting-started"))
```

Ordinary remote content should come over HTTPS, not through a custom scheme.
Handler implementation and cancellation are covered in
[scheme handler notes](references/local-content-and-custom-schemes.md).

## View modifiers

- `webViewBackForwardNavigationGestures(_:)`: turn on swipe back and forward
  when people will visit several pages.
- `findNavigator(isPresented:)`: Find in Page for long, document-like content.
- `webViewScrollPosition(_:)` and `webViewOnScrollGeometryChange(for:of:action:)`:
  sync scrolling only when there is a sidebar, a table of contents or another
  explicit navigation control.

The HIG asks for back and forward support where it helps, but an app's web
view should not grow into a general-purpose browser.

## Common mistakes

- Reaching for a `WKWebView` wrapper in a SwiftUI app that targets iOS 26+.
- Running OAuth inside an embedded web view.
- Starting with `WebView(url:)` and bolting on `WebPage` later once state,
  JavaScript or navigation control turns out to be needed.
- Treating `callJavaScript` as if it were `WKScriptMessageHandler`.
- Keeping every link in the app when other domains should open outside it.
- Building a browser shell (address bar, tabs) around the web view.
- Using a custom scheme for content that should load over HTTPS.
- Touching a `WebPage` off the main actor; the type is `@MainActor`.

## Review checklist

- [ ] iOS 26+ screens start from `WebView` plus `WebPage`
- [ ] Sign-in goes through `ASWebAuthenticationSession`
- [ ] A `WebPage` exists wherever state, JavaScript or policy control is needed
- [ ] The navigation decider only intercepts URLs the app owns or reroutes
- [ ] Other domains open outside the app where that is the better experience
- [ ] JavaScript results are cast defensively
- [ ] Custom schemes serve only genuine app-owned resources
- [ ] Multi-page browsing has back and forward gestures or controls
- [ ] The screen offers something native and specific, not a wrapped website
- [ ] Each remaining `WKWebView` has a reason: an older deployment target or a missing API

## References

- [page loading notes](references/loading-and-observation.md): URL-only views, controlled loading, progress and title, navigation events, ephemeral pages, user agents
- [policy and script notes](references/navigation-and-javascript.md): deciders, external links, calling JavaScript, arguments, page-to-app signals
- [scheme handler notes](references/local-content-and-custom-schemes.md): scheme handlers, responses, bundled files, cancellation
- [migration notes](references/migration-and-fallbacks.md): moving off `WKWebView` wrappers, Safari and sign-in boundaries, testing
