How to inject JavaScript code into a WKWebView in Swift?

To inject JavaScript code into a WKWebView in Swift, you can use the evaluateJavaScript(_:completionHandler:) method provided by WKWebView.

Here is an example code snippet that loads a web page and then injects a JavaScript code snippet that changes the background color of the document:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a WKWebView instance
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)

        // Load a web page
        if let url = URL(string: "https://www.example.com") {
            webView.load(URLRequest(url: url))
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Inject JavaScript code
        let script = "document.body.style.backgroundColor = '#ff0000';"
        webView.evaluateJavaScript(script, completionHandler: nil)
    }
}

In this example, the webView(_:didFinish:) method is called when the web page has finished loading. Inside this method, the evaluateJavaScript(_:completionHandler:) method is used to inject a JavaScript code snippet that changes the background color of the document to red.

You can replace the example JavaScript code with any code that you want to inject into the WKWebView.

A pat on the back !!