A custom web bridge implementation between JavaScript and Swift, built on top of cybozu/WebUI with additional extensions for streamlined communication.
Note
This sample code aims to solve the challenge: "Exchange data between a WebView and the app using pure SwiftUI, minimizing reliance on AppKit/UIKit."
Feedback and contributions to improve this implementation—whether through Issues or Pull Requests—are welcome!
Because the project relies on cybozu/WebUI, some features require the following minimum os versions below:
- iOS: 16.4
- macOS: 13.3
This project provides a type-safe, extensible bridge for sending messages between JavaScript running in WKWebView and Swift code. It leverages WebUI's core functionality while adding custom handlers, message routing, and SwiftUI integrations.
- JSMessageRouter.swift: Central router that dispatches incoming JavaScript messages to appropriate handlers based on message type.
- WebScriptHandler.swift: WKScriptMessageHandler implementation that receives messages from JavaScript and forwards them to the router.
- Factory/WebViewFactory.swift: Factory for creating configured WKWebView instances with the bridge setup.
- Message/JSBridgeMessage.swift: Data structure representing messages sent from JavaScript to Swift.
- Response/SwiftMessageResponse.swift: Structure for responses sent back from Swift to JavaScript.
- ViewExtension/View+JSMessage.swift: SwiftUI view extension for handling JS messages in views.
- JSON/JsonCleaner.swift: Utility for cleaning and encoding JSON data, with fallback handling.
- WebUIDelegate+iOS.swift: iOS-specific WKUIDelegate for handling web UI dialogs (alerts, confirms, file inputs).
- WebUIDelegate+macOS.swift: macOS-specific WKUIDelegate for native AppKit dialogs.
- WebPageView.swift: SwiftUI view wrapping WKWebView with bridge integration.
- ContentView.swift: Main app view demonstrating the bridge usage.
- Webpages/PageA/webpageA.html: Sample HTML page with JavaScript that demonstrates sending messages to Swift.
Important
In this example we use a local webpage. If you want to interact with an online webpage, make sure to enable Incoming/Outgoing connections in Target > Signing & Capabilities > All > App Sandbox
- Create a WebPageView with a URL or HTML content.
- Use the View extension
onJSMessageto handle incoming messages in your SwiftUI views. - Send responses back to JavaScript using the message handler's response methods.
The bridge enables bidirectional communication: JavaScript can call Swift functions and pass data, while Swift can execute JavaScript and return results.