swiftui-webkit
dpearson2699/swift-ios-skills
Embed and control web content in SwiftUI using native WebKit APIs for iOS 26+.
What is swiftui-webkit?
SwiftUI WebKit lets you embed and manage web content directly in SwiftUI apps using Apple's native WebKit-for-SwiftUI APIs (iOS 26+, iPadOS 26+, macOS 26+, visionOS 26+). Use it when your app needs integrated web surfaces, app-owned HTML content, JavaScript interaction, or custom navigation control without relying on external browsers.
- Display web content via WebView with simple URL loading or advanced WebPage state management
- Observe page state including title, URL, loading progress, and navigation events in real time
- Execute JavaScript functions against the page and retrieve results with type safety
- Implement custom navigation policies to keep internal links embedded and route external links to Safari
- Load local HTML files, bundled assets, and custom URL schemes for offline or app-owned content
- Customize WebView behavior through WebPage.Configuration and NavigationPreferences
How to install swiftui-webkit
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill swiftui-webkit- iOS 26, iPadOS 26, macOS 26, or visionOS 26 or later
- SwiftUI project with WebKit framework imported
- For custom URL schemes: URLSchemeHandler implementation
How to use swiftui-webkit
- 1.Import WebKit and SwiftUI in your view file
- 2.Create a WebPage instance as @State or in an @Observable model if you need state observation
- 3.Call page.load(url:) or page.load(URLRequest:) to load content
- 4.Embed WebView(page) in your SwiftUI hierarchy
- 5.Optionally implement WebPage.NavigationDeciding to customize navigation behavior
- 6.Optionally call page.callJavaScript() to interact with page content from Swift
Use cases
- Building in-app article or detail views backed by HTML/CSS/JavaScript
- Creating help centers or in-app documentation without leaving the app
- Loading bundled offline content or custom-scheme resources
- Intercepting navigation to route external links to Safari while keeping internal navigation embedded
- Executing JavaScript to extract page data or control page behavior from Swift code
- iOS/iPadOS app developers targeting iOS 26 or later
- macOS and visionOS app developers needing embedded web surfaces
- Teams migrating from UIKit WKWebView wrappers to modern SwiftUI
- Developers building documentation, help, or content-heavy features in SwiftUI
swiftui-webkit FAQ
Use WebView + WebPage for embedded app-owned content in modern SwiftUI (iOS 26+). Use SFSafariViewController for modal Safari-like browsing. Use ASWebAuthenticationSession for OAuth. Fall back to WKWebView only if you need features below iOS 26 or legacy-only WebKit APIs.
No. Use ASWebAuthenticationSession for OAuth and third-party authentication flows instead. WebKit-for-SwiftUI is for app-owned content, not external authentication.
Implement WebPage.NavigationDeciding in your navigation policy handler. Check the request URL's host and return .allow for internal domains or .cancel for external ones, then use openURL to route external links to Safari.
Yes. Use page.callJavaScript(_:arguments:in:contentWorld:) to execute JavaScript functions and retrieve results. Pass Swift values via the arguments dictionary and cast the returned Any to your expected type.
Create a WebPage.Configuration, assign a URLSchemeHandler for a custom scheme, and load URLs under that scheme. This works for bundled documentation, offline assets, or app-provided resources.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: swiftui-webkit description: "Embeds and controls web content in SwiftUI with WebKit for SwiftUI, including WebView, WebPage, navigation policies, JavaScript execution, observable page state, link interception, local HTML or data loading, and custom URL schemes. Use when building iOS 26+ article/detail views, help centers, in-app documentation, or other embedded web experiences backed by HTML, CSS, and JavaScript."
SwiftUI WebKit
Embed and manage web content in SwiftUI using the native WebKit-for-SwiftUI APIs introduced for iOS 26, iPadOS 26, macOS 26, and visionOS 26. Use this skill when the app needs an integrated web surface, app-owned HTML content, JavaScript-backed page interaction, or custom navigation policy control.
Contents
- Choose the Right Web Container
- Displaying Web Content
- Loading and Observing with WebPage
- Navigation Policies
- JavaScript Integration
- Local Content and Custom URL Schemes
- WebView Customization
- Common Mistakes
- Review Checklist
- References
Choose the Right Web Container
Use the narrowest tool that matches the job.
| Need | Default choice |
|---|---|
| Embedded app-owned web content in SwiftUI | WebView + WebPage |
| iOS/iPadOS modal browsing with Safari behavior | SFSafariViewController |
| macOS or visionOS browse-out behavior | openURL / default browser |
| OAuth or third-party sign-in | ASWebAuthenticationSession |
| Back-deploy below iOS 26 or use missing legacy-only WebKit features | WKWebView fallback |
Prefer WebView and WebPage for modern SwiftUI apps targeting iOS 26+ when the new API surface covers the feature. Apple’s WWDC25 guidance frames existing UIKit/AppKit WebKit wrappers in SwiftUI apps as good candidates to try migrating, not as a blanket mandate to delete every fallback.
Do not use embedded web views for OAuth. That stays an ASWebAuthenticationSession flow.
Displaying Web Content
Use the simple WebView(url:) form when the app only needs to render a URL and SwiftUI state drives navigation.
import SwiftUI
import WebKit
struct ArticleView: View {
let url: URL
var body: some View {
WebView(url: url)
}
}
Create a WebPage when the app needs to load requests directly, observe state, call JavaScript, or customize navigation behavior.
A WebPage can be associated with only one WebView at a time. Create separate WebPage instances for multiple visible web views.
@Observable
@MainActor
final class ArticleModel {
let page = WebPage()
func load(_ url: URL) async throws {
for try await _ in page.load(URLRequest(url: url)) {
}
}
}
struct ArticleDetailView: View {
@State private var model = ArticleModel()
let url: URL
var body: some View {
WebView(model.page)
.task {
try? await model.load(url)
}
}
}
See references/loading-and-observation.md for full examples.
Loading and Observing with WebPage
WebPage is an @MainActor observable type. Use it when you need page state in SwiftUI.
Common loading entry points:
load(URLRequest)load(URL)load(html:baseURL:)load(_:mimeType:characterEncoding:baseURL:)
Common observable properties:
titleurlisLoadingestimatedProgresscurrentNavigationEventbackForwardList
struct ReaderView: View {
@State private var page = WebPage()
var body: some View {
WebView(page)
.navigationTitle(page.title ?? "Loading")
.overlay {
if page.isLoading {
ProgressView(value: page.estimatedProgress)
}
}
.task {
do {
for try await _ in page.load(URLRequest(url: URL(string: "https://example.com")!)) {
}
} catch {
// Handle load failure.
}
}
}
}
When you need to react to every navigation, observe the navigation sequence rather than only checking a single property.
Task {
do {
for try await event in page.navigations {
// Handle started, redirect, committed, or finished events.
}
} catch {
// Handle WebPage.NavigationError or cancellation.
}
}
See references/loading-and-observation.md for stronger patterns and the load-sequence examples.
Navigation Policies
Use WebPage.NavigationDeciding to allow, cancel, or customize navigations based on the request or response.
Typical uses:
- keep app-owned domains inside the embedded web view
- cancel external domains and hand them off with
openURL - intercept special callback URLs
- tune
NavigationPreferences
@MainActor
final class ArticleNavigationDecider: WebPage.NavigationDeciding {
var urlToOpenExternally: URL?
func decidePolicy(
for action: WebPage.NavigationAction,
preferences: inout WebPage.NavigationPreferences
) async -> WKNavigationActionPolicy {
guard let url = action.request.url else { return .allow }
if url.host == "example.com" {
return .allow
}
urlToOpenExternally = url
return .cancel
}
}
Keep app-level deep-link routing in the navigation skill. This skill owns navigation that happens inside embedded web content.
See references/navigation-and-javascript.md for complete patterns.
JavaScript Integration
Use callJavaScript(_:arguments:in:contentWorld:) to evaluate JavaScript functions against the page.
Pass a JavaScript function body, not a wrapped function declaration or call expression. Prefer arguments for Swift-provided values instead of interpolating untrusted strings into the script.
let script = """
const headings = [...document.querySelectorAll('h1, h2')];
return headings.map(node => ({
id: node.id,
text: node.textContent?.trim()
}));
"""
let result = try await page.callJavaScript(script)
let headings = result as? [[String: Any]] ?? []
You can pass values through the arguments dictionary and cast the returned Any into the Swift type you actually need.
let result = try await page.callJavaScript(
"return document.getElementById(sectionID)?.getBoundingClientRect().top ?? null;",
arguments: ["sectionID": selectedSectionID]
)
Handle empty and JavaScript null results deliberately: no explicit return produces nil, while an explicit JavaScript null returns NSNull.
Important boundary: the native SwiftUI WebKit API clearly supports Swift-to-JavaScript calls, but it does not expose an obvious direct replacement for WKScriptMessageHandler. If you need coarse JS-to-native signaling, a custom navigation or callback-URL pattern can work, but document it as a workaround pattern, not a guaranteed one-to-one replacement.
See references/navigation-and-javascript.md.
Local Content and Custom URL Schemes
Use WebPage.Configuration and URLSchemeHandler when the app needs bundled HTML, offline documents, or app-provided resources under a custom scheme.
var configuration = WebPage.Configuration()
configuration.urlSchemeHandlers[URLScheme("docs")!] = DocsSchemeHandler(bundle: .main)
let page = WebPage(configuration: configuration)
for try await _ in page.load(URL(string: "docs://article/welcome")!) {
}
Use this for:
- bundled documentation or article content
- offline HTML/CSS/JS assets
- app-owned resource loading under a custom scheme
Do not overuse custom schemes for normal remote content. Prefer standard HTTPS for server-hosted pages.
See references/local-content-and-custom-schemes.md.
WebView Customization
Use WebView modifiers to match the intended browsing experience.
Useful modifiers and related APIs:
webViewBackForwardNavigationGestures(_:)findNavigator(isPresented:)webViewScrollPosition(_:)webViewOnScrollGeometryChange(...)
Apply them only when the user experience needs them.
- Enable back/forward gestures when people are likely to visit multiple pages.
- Add Find in Page when the content is document-like.
- Sync scroll position only when the app has a sidebar, table of contents, or other explicit navigation affordance.
Apple’s HIG also applies here: support back/forward navigation when appropriate, but do not turn an app web view into a general-purpose browser.
Common Mistakes
- Using
WKWebViewwrappers by default in an iOS 26+ SwiftUI app instead of starting withWebViewandWebPage - Using embedded web views for OAuth instead of
ASWebAuthenticationSession - Reaching for
WebPageonly after building a plainWebView(url:)path that now needs state, JS, or navigation control - Treating
callJavaScriptas a direct replacement forWKScriptMessageHandler - Passing a callable JavaScript wrapper to
callJavaScriptinstead of only the function body - Iterating
page.navigationswithouttry/catcheven though navigation failure terminates the sequence by throwing - Binding the same
WebPageto multiple visibleWebViewvalues - Keeping all links inside the app when external domains should open outside the embedded surface
- Treating
SFSafariViewControlleras the cross-platform browse-out answer on macOS or visionOS instead of using default-browser/openURL behavior - Building a browser-style app shell around WebView instead of a focused embedded experience
- Using custom URL schemes for content that should just load over HTTPS
- Forgetting that
WebPageis main-actor-isolated
Review Checklist
-
WebViewandWebPageare the default path for iOS 26+ SwiftUI web content -
ASWebAuthenticationSessionis used for auth flows instead of embedded web views -
WebPageis used whenever the app needs state observation, JS calls, or policy control - Navigation policies only intercept the URLs the app actually owns or needs to reroute
- External domains open externally when appropriate
- JavaScript return values are cast defensively to concrete Swift types
-
callJavaScriptuses a function body and passes Swift values througharguments -
page.navigationsloops usefor try awaitand handle thrown navigation errors - Each visible
WebView(page)owns a distinctWebPage - Custom URL schemes are used only for real app-owned resources
- Back/forward gestures or controls are enabled when multi-page browsing is expected
-
SFSafariViewControlleris limited to iOS/iPadOS Safari-style modal browsing; macOS and visionOS browse-out flows use platform default browser behavior - The web experience adds focused native value instead of behaving like a thin browser shell
- Fallback to
WKWebViewis justified by deployment target or missing API needs
References
- Loading and observation: references/loading-and-observation.md
- Navigation and JavaScript: references/navigation-and-javascript.md
- Local content and custom schemes: references/local-content-and-custom-schemes.md
- Migration and fallbacks: references/migration-and-fallbacks.md
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

tabletopkit
Build multiplayer spatial board games on visionOS with TabletopKit, handling boards, pieces, turns, and FaceTime synchronization.

tipkit
Implement Apple TipKit feature-discovery UI for iOS 17+ apps with inline tips, popovers, rules, and CloudKit sync.

vision-framework
Detect text, faces, barcodes, and objects in iOS images and video using on-device Vision framework.

weatherkit
Fetch WeatherKit forecasts, alerts, and attribution for iOS 18+ apps using Swift 6.3.

widgetkit
Build Home Screen, Lock Screen, Control Center, and StandBy widgets for iOS with timeline providers and interactive controls.

tech-news-digest
Generate tech news digests with unified source model, quality scoring, and multi-format output. Six-source data collection from RSS feeds, Twitter/X KOLs, GitHub releases, GitHub Trending, Reddit, and web search. Pipeline-based scripts with retry mechanisms and deduplication. Supports Discord, email, and markdown templates.