webkit-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WebKit Integration for SwiftUI

SwiftUI 中的 WebKit 集成

Embed and control web content in SwiftUI apps using the native
WebView
struct and
WebPage
observable class. Covers loading, navigation, JavaScript execution, and view customization.
使用原生的
WebView
结构体和
WebPage
可观察类,在SwiftUI应用中嵌入并控制网页内容。涵盖内容加载、导航、JavaScript执行及视图自定义功能。

When This Skill Activates

本技能适用场景

  • User wants to display web content inside a SwiftUI app
  • User needs to load URLs, HTML strings, or data blobs in a web view
  • User asks about JavaScript interop from SwiftUI
  • User needs navigation control (back, forward, reload) for embedded web content
  • User wants to customize web view behavior (gestures, text selection, link previews)
  • User needs to capture snapshots or export PDFs from web content
  • User asks about intercepting navigation requests or custom URL schemes
  • User wants to configure private browsing or custom user agents
  • 用户希望在SwiftUI应用中展示网页内容
  • 用户需要在网页视图中加载URL、HTML字符串或数据二进制对象
  • 用户询问SwiftUI与JavaScript的交互方法
  • 用户需要对嵌入的网页内容进行导航控制(后退、前进、刷新)
  • 用户希望自定义网页视图行为(手势、文本选择、链接预览)
  • 用户需要捕获网页内容快照或导出PDF
  • 用户询问拦截导航请求或自定义URL协议的方法
  • 用户希望配置隐私浏览或自定义用户代理

Decision Tree

决策树

What do you need?
|
+-- Display a URL or HTML content
|   +-- Simple, no interaction needed
|   |   +-- WebView(url:) --> see webview-basics.md
|   +-- Need loading state, reload, custom config
|       +-- WebPage + WebView(page) --> see webview-basics.md
|
+-- Navigate programmatically (back, forward, intercept)
|   +-- Back/forward list, navigation events
|   |   +-- see navigation.md
|   +-- Intercept or cancel navigation requests
|       +-- NavigationDeciding protocol --> see navigation.md
|
+-- Execute JavaScript or communicate with web content
|   +-- callJavaScript, arguments, content worlds
|       +-- see javascript-advanced.md
|
+-- Capture snapshots, export PDF, web archive
|   +-- page.snapshot(), page.pdf(), page.webArchiveData()
|       +-- see javascript-advanced.md
|
+-- Handle custom URL schemes
    +-- URLSchemeHandler protocol --> see javascript-advanced.md
你需要什么?
|
+-- 展示URL或HTML内容
|   +-- 简单展示,无需交互
|   |   +-- WebView(url:) --> 查看 webview-basics.md
|   +-- 需要加载状态、刷新、自定义配置
|       +-- WebPage + WebView(page) --> 查看 webview-basics.md
|
+-- 程序化导航(后退、前进、拦截)
|   +-- 后退/前进列表、导航事件
|   |   +-- 查看 navigation.md
|   +-- 拦截或取消导航请求
|       +-- NavigationDeciding 协议 --> 查看 navigation.md
|
+-- 执行JavaScript或与网页内容通信
|   +-- callJavaScript、参数、内容环境
|       +-- 查看 javascript-advanced.md
|
+-- 捕获快照、导出PDF、网页归档
|   +-- page.snapshot(), page.pdf(), page.webArchiveData()
|       +-- 查看 javascript-advanced.md
|
+-- 处理自定义URL协议
    +-- URLSchemeHandler 协议 --> 查看 javascript-advanced.md

API Availability

API 可用性

APIMinimum OSImport
WebView
iOS 26 / macOS 26
SwiftUI
+
WebKit
WebPage
iOS 26 / macOS 26
WebKit
WebPage.Configuration
iOS 26 / macOS 26
WebKit
NavigationDeciding
iOS 26 / macOS 26
WebKit
WKContentWorld
iOS 14 / macOS 11
WebKit
WKSnapshotConfiguration
iOS 11 / macOS 10.13
WebKit
WKPDFConfiguration
iOS 14 / macOS 11
WebKit
API最低系统版本导入框架
WebView
iOS 26 / macOS 26
SwiftUI
+
WebKit
WebPage
iOS 26 / macOS 26
WebKit
WebPage.Configuration
iOS 26 / macOS 26
WebKit
NavigationDeciding
iOS 26 / macOS 26
WebKit
WKContentWorld
iOS 14 / macOS 11
WebKit
WKSnapshotConfiguration
iOS 11 / macOS 10.13
WebKit
WKPDFConfiguration
iOS 14 / macOS 11
WebKit

Quick Start

快速入门

Simplest Usage

最简用法

swift
import SwiftUI
import WebKit

struct BrowserView: View {
    var body: some View {
        WebView(url: URL(string: "https://developer.apple.com")!)
    }
}
swift
import SwiftUI
import WebKit

struct BrowserView: View {
    var body: some View {
        WebView(url: URL(string: "https://developer.apple.com")!)
    }
}

With WebPage for Full Control

使用WebPage实现完全控制

swift
import SwiftUI
import WebKit

struct ControlledBrowserView: View {
    @State private var page = WebPage()

    var body: some View {
        WebView(page)
            .onAppear {
                page.load(URLRequest(url: URL(string: "https://developer.apple.com")!))
            }
    }
}
swift
import SwiftUI
import WebKit

struct ControlledBrowserView: View {
    @State private var page = WebPage()

    var body: some View {
        WebView(page)
            .onAppear {
                page.load(URLRequest(url: URL(string: "https://developer.apple.com")!))
            }
    }
}

Top Mistakes

常见错误

MistakeProblemFix
Using
WebView(url:)
when you need navigation control
No access to back/forward, reload, or eventsUse
WebPage
+
WebView(page)
Forgetting
import WebKit
alongside
import SwiftUI
WebView
is in SwiftUI but
WebPage
requires WebKit
Always import both
Not observing
currentNavigationEvent
Missing loading states, errors go unnoticedUse
onChange(of: page.currentNavigationEvent)
Calling
callJavaScript
before page finishes loading
Script fails because DOM is not readyWait for
.finished
navigation event
Using persistent data store for private browsingUser data is saved to diskUse
.nonPersistent()
on
WebsiteDataStore
Not handling
nil
return from
decidePolicyFor(navigationAction:)
Navigation proceeds when it should be cancelledReturn
nil
to cancel, return
NavigationPreferences
to allow
Passing JavaScript without argument bindingVulnerable to injection, hard to debugUse
arguments:
parameter for named values
错误操作问题解决方法
需要导航控制时仍使用
WebView(url:)
无法访问后退/前进、刷新功能或导航事件使用
WebPage
+
WebView(page)
组合
仅导入
SwiftUI
而忘记导入
WebKit
WebView
属于SwiftUI,但
WebPage
需要WebKit框架
始终同时导入两个框架
未监听
currentNavigationEvent
无法获取加载状态,错误无法被察觉使用
onChange(of: page.currentNavigationEvent)
监听
页面加载完成前调用
callJavaScript
DOM未就绪导致脚本执行失败等待
.finished
导航事件后再执行
为隐私浏览使用持久化数据存储用户数据会被保存到磁盘
WebsiteDataStore
上使用
.nonPersistent()
decidePolicyFor(navigationAction:)
未处理
nil
返回值
应取消的导航仍会继续返回
nil
以取消导航,返回
NavigationPreferences
以允许导航
传递JavaScript时未绑定参数易受注入攻击且难以调试使用
arguments:
参数传递命名值

Review Checklist

检查清单

  • Using
    WebPage
    when any control beyond simple display is needed
  • Both
    SwiftUI
    and
    WebKit
    are imported
  • Navigation events observed for loading indicators and error handling
  • JavaScript execution waits for page to finish loading
  • Private browsing uses
    .nonPersistent()
    data store
  • Navigation interception returns correct values (preferences to allow, nil to cancel)
  • JavaScript arguments passed via
    arguments:
    parameter, not string interpolation
  • Custom URL scheme handler registered on configuration before page loads
  • Find-in-page enabled with
    findNavigator(isPresented:)
    if needed
  • Appropriate gesture and interaction modifiers applied (back/forward, magnification, text selection)
  • Content background customized if needed for visual integration
  • 当需要简单展示之外的控制功能时,使用
    WebPage
  • 已同时导入
    SwiftUI
    WebKit
  • 已监听导航事件以实现加载指示器和错误处理
  • JavaScript执行等待页面加载完成
  • 隐私浏览使用
    .nonPersistent()
    数据存储
  • 导航拦截返回正确值(返回偏好设置允许导航,返回nil取消导航)
  • 通过
    arguments:
    参数传递JavaScript参数,而非字符串插值
  • 在页面加载前已在配置中注册自定义URL协议处理器
  • 若需要,已通过
    findNavigator(isPresented:)
    启用页面内搜索
  • 已应用合适的手势和交互修饰符(后退/前进、缩放、文本选择)
  • 若需要,已自定义内容背景以实现视觉集成

Reference Files

参考文件

FileContents
webview-basics.md
WebView creation, WebPage setup, configuration, find-in-page, customization modifiers
navigation.md
Loading content, back/forward list, navigation events, NavigationDeciding protocol
javascript-advanced.md
JavaScript execution, content worlds, snapshots, PDF export, custom URL schemes
文件内容
webview-basics.md
WebView创建、WebPage设置、配置、页面内搜索、自定义修饰符
navigation.md
内容加载、后退/前进列表、导航事件、NavigationDeciding协议
javascript-advanced.md
JavaScript执行、内容环境、快照、PDF导出、自定义URL协议

Cross-References

交叉参考

  • For macOS window management around web views, see
    macos/architecture-patterns/
  • For navigation architecture that hosts a web view, see
    ios/navigation-patterns/
  • For Liquid Glass design around web content, see
    design/liquid-glass/
  • 关于网页视图的macOS窗口管理,请查看
    macos/architecture-patterns/
  • 关于承载网页视图的导航架构,请查看
    ios/navigation-patterns/
  • 关于网页内容的Liquid Glass设计,请查看
    design/liquid-glass/

References

官方参考