WebView
SkipWeb provides an embedded WebView for Skip Lite transpiled Swift. On iOS it uses a WKWebView ↗ and on Android it uses an android.webkit.WebView ↗.
A simple example of using an embedded WebView with a static URL can be seen:
import Foundationimport SwiftUIimport SkipWeb
struct EmbeddedWebView : View { let url: URL
var body: some View { WebView(url: url) }}Customization
Section titled “Customization”The WebView ↗ is backed by a
WebEngine ↗.
It can be configured with a WebEngineConfiguration ↗ instance. For example:
import Foundationimport SwiftUIimport SkipWeb
struct ConfigurableWebView : View { let navigator: WebViewNavigator = WebViewNavigator(initialURL: URL("https://skip.dev")!) @ObservedObject var configuration: WebEngineConfiguration @Binding var state: WebViewState
var body: some View { WebView(configuration: configuration, navigator: navigator, state: $state) }}JavaScript
Section titled “JavaScript”JavaScript can be executed against the browser with:
let json: String? = try await navigator.evaluateJavaScript(javaScriptInput)The JSON string that is returned may be an object, or may be fragmentary (that is, a top-level string or number, null, or array), so care should be taken when attempting to deserialize it.
Note: since the browser’s JavaScript engines are quite different (V8 and Blink on Android versus JavaScript Core and WebKit on iOS), resuts from script execution are expected to vary somewhat depending on the different quirks of the implementations.
A full example of a browser that can evaluate JavaScript and display the results in a sheet can be implemented with the following View:
import SwiftUIimport SkipWeb
/// This component uses the `SkipWeb` module from https://source.skip.dev/skip-webstruct WebViewPlayground: View { @State var config = WebEngineConfiguration() @State var navigator = WebViewNavigator() @State var state = WebViewState() @State var showScriptSheet = false @State var javaScriptInput = "document.body.innerText" @State var javaScriptOutput = ""
var body: some View { VStack { WebView(configuration: config, navigator: navigator, url: URL(string: "https://skip.dev")!, state: $state) } .toolbar { Button { navigator.goBack() } label: { Image(systemName: "arrow.left") } .disabled(!state.canGoBack) .accessibilityLabel(Text("Back"))
Button { navigator.reload() } label: { Image(systemName: "arrow.clockwise.circle") } .accessibilityLabel(Text("Reload"))
Button { navigator.goForward() } label: { Image(systemName: "arrow.forward") } .disabled(!state.canGoForward) .accessibilityLabel(Text("Forward"))
Button { self.showScriptSheet = true } label: { Image(systemName: "ellipsis") } .accessibilityLabel(Text("Evaluate JavaScript")) } .navigationTitle(state.pageTitle ?? "WebView") .navigationBarTitleDisplayMode(.inline) .sheet(isPresented: $showScriptSheet) { NavigationStack { VStack { TextField("JavaScript", text: $javaScriptInput) .textFieldStyle(.roundedBorder) .autocorrectionDisabled() .keyboardType(.asciiCapable) // also disables smart quotes .textInputAutocapitalization(.never) .onSubmit(of: .text) { evaluateJavaScript() } .padding() Text("Output") .font(.headline) TextEditor(text: $javaScriptOutput) .font(Font.body.monospaced()) .border(Color.secondary) .padding() } .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Evaluate Script") { evaluateJavaScript() } .disabled(javaScriptInput.isEmpty) }
ToolbarItem(placement: .cancellationAction) { Button("Close", role: .cancel) { showScriptSheet = false } } } } } }
/// Evaluate the script specified in the sheet func evaluateJavaScript() { let navigator = self.navigator Task { var scriptResult: String = "" do { if let resultJSON = try await navigator.evaluateJavaScript(javaScriptInput) { // top-level fragments are nicer to display as strings, so we try to deserialize them if let topLevelString = try? JSONSerialization.jsonObject(with: resultJSON.data(using: .utf8)!, options: .fragmentsAllowed) as? String { scriptResult = topLevelString } else { scriptResult = resultJSON } } } catch { scriptResult = error.localizedDescription } Task { @MainActor in self.javaScriptOutput = scriptResult } } }}Window Creation & Popups
Section titled “Window Creation & Popups”SkipWeb exposes popup/window creation through SkipWebUIDelegate on WebEngineConfiguration.
This delegate API lets host apps decide whether a popup should open and which child WebEngine should back it.
For full API details and usage examples, see SkipWebUIDelegate.md.
The createWebViewWith callback returns a WebEngine?:
- Return
nilto deny child-window creation. - Return a child
WebEngineto allow child-window creation.
JavaScript popup behavior can be configured with:
WebEngineConfiguration.javaScriptCanOpenWindowsAutomatically(maps to both iOS and Android platform settings).
Platform callback semantics
Section titled “Platform callback semantics”Callbacks are platform-agnostic, but invocation source differs:
| Callback | iOS (WebKit) | Android |
|---|---|---|
webView(_:createWebViewWith:platformContext:) | Called from WKUIDelegate.createWebViewWith | Called from WebChromeClient.onCreateWindow |
webViewDidClose(_:child:) | Called from WKUIDelegate.webViewDidClose | Called from WebChromeClient.onCloseWindow |
WebWindowRequest.targetURL may be nil on Android during onCreateWindow.
PlatformCreateWindowContext aliases WebKitCreateWindowParams on iOS and AndroidCreateWindowParams on Android.
iOS WebKit popup contract
Section titled “iOS WebKit popup contract”When handling iOS popups through WKUIDelegate.createWebViewWith, WebKit requires that the returned child WKWebView be initialized with the exact WKWebViewConfiguration provided by WebKit for that callback.
If this contract is violated, WebKit can raise NSInternalInconsistencyException with:
Returned WKWebView was not created with the given configuration.
SkipWeb validates this contract at popup creation time:
- A warning is logged when verification cannot be performed.
- An error is logged when a contract violation is detected.
For iOS parity, return a child created with platformContext.makeChildWebEngine(...).
By default this mirrors the parent WebEngineConfiguration and inspectability on the popup child. Pass an explicit configuration only when you intentionally want the child to diverge.
This default mirroring is configuration-level. Platform delegate assignments on the returned child (WKUIDelegate, WKNavigationDelegate) are not automatically copied from the parent, so assign them explicitly if your app depends on that behavior.
Contribution
Section titled “Contribution”Many delegates that are provided by WKWebView are not yet implemented in this project,
and so deeper customization may require custom implementation work.
To implement these, you may need to fork the repository and add it to your workspace,
as described in the Contributing guide.
Please consider creating a Pull Request ↗
with features and fixes that you create, as this benefits the entire Skip community.
Building
Section titled “Building”This project is a free Swift Package Manager module that uses the Skip plugin to transpile Swift into Kotlin.
Building the module requires that Skip be installed using
Homebrew ↗ with brew install skiptools/skip/skip.
This will also install the necessary build prerequisites:
Kotlin, Gradle, and the Android build tools.
Testing
Section titled “Testing”The module can be tested using the standard swift test command
or by running the test target for the macOS destination in Xcode,
which will run the Swift tests as well as the transpiled
Kotlin JUnit tests in the Robolectric Android simulation environment.
Parity testing can be performed with skip test,
which will output a table of the test results for both platforms.
Contributing
Section titled “Contributing”We welcome contributions to this package in the form of enhancements and bug fixes.
The general flow for contributing to this and any other Skip package is:
- Fork this repository and enable actions from the “Actions” tab
- Check out your fork locally
- When developing alongside a Skip app, add the package to a shared workspace to see your changes incorporated in the app
- Push your changes to your fork and ensure the CI checks all pass in the Actions tab
- Add your name to the Skip Contributor Agreement ↗
- Open a Pull Request from your fork with a description of your changes