Exploring WebView in Swift: An In-depth Guide with JavaScript Interaction

In modern app development, integrating web content into native applications is a common requirement. SwiftUI provides a powerful component called WebView that allows you to embed web content seamlessly within your iOS app. In this tutorial, we’ll explore how to use WebView in Swift, and dive into the exciting world of JavaScript interaction with loaded web pages.

Getting Started with WebView

To begin, create a new Swift project in Xcode. We’ll be using SwiftUI for this tutorial. Ensure that your project is targeting iOS 14 or later, as WebView is available starting from iOS 14. Import the necessary framework:

import SwiftUI
import WebKit

Embedding WebView

Adding a WebView to your SwiftUI view is straightforward. Here’s a basic example:

struct ContentView: View {
    var body: some View {
        WebView(url: URL(string: "https://www.example.com")!)
    }
}

In this example:
– We create a `ContentView` struct that conforms to the `View` protocol.
– Inside the `body` property, we instantiate a WebView component and provide a URL to load.

Creating the WebView Component

Now, let’s define the WebView component:

struct WebView: UIViewRepresentable {
    let url: URL

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let request = URLRequest(url: url)
        uiView.load(request)
    }
}

In this code:
– We create a WebView struct that conforms to `UIViewRepresentable`, allowing us to use UIKit components in SwiftUI.
– Inside `makeUIView`, we initialize a `WKWebView`, which is a subclass of `UIView` provided by WebKit framework.
– In `updateUIView`, we load the specified URL into the `WKWebView`.

JavaScript Interaction

Interacting with JavaScript on the loaded web page opens up a whole new dimension of possibilities. Let’s explore how to execute JavaScript code and receive results within our Swift app.

Executing JavaScript

You can execute JavaScript code within a `WKWebView` using the `evaluateJavaScript(_:completionHandler:)` method. Here’s how you can call a JavaScript function:

func executeJavaScript(_ script: String, completionHandler: ((Any?, Error?) -> Void)? = nil) {
    webView.evaluateJavaScript(script, completionHandler: completionHandler)
}

Example: Getting Page Title

Let’s create a function to retrieve the title of the loaded web page using JavaScript:

func getPageTitle(completion: @escaping (String?, Error?) -> Void) {
    let script = "document.title"
    executeJavaScript(script) { result, error in
        if let title = result as? String {
            completion(title, nil)
        } else {
            completion(nil, error)
        }
    }
}

Example: Injecting JavaScript

You can also inject JavaScript code into the web page using `WKUserScript`. For example, let’s inject a script to change the background color of the loaded page:

func injectJavaScript() {
    let script = """
        document.body.style.backgroundColor = 'lightblue';
    """
    let userScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    webView.configuration.userContentController.addUserScript(userScript)
}

Conclusion

You’ve now learned how to integrate WebView into your SwiftUI app and interact with JavaScript on loaded web pages. Whether you’re building a hybrid app or incorporating web content into your native iOS app, WebView provides a seamless integration experience. Experiment with various JavaScript interactions to create rich and dynamic user experiences. Happy coding!

Leave a Reply