Skip to content
Advertisement

WKWebView iOS linking Javascript File

I’m having trouble getting a javascript file to run from inside a UIViewRepresentable WKWebView. This is probably a simple question with a simple answer, but I cannot seem to figure this out. I’m new to Swift and iOS programming.

I’d like to link to a javascript file from inside a String of HTML that is passed to a UIViewRepresentable of WKWebView. As far as I can see the Javascript is not running.

ContentView:

import SwiftUI

struct ContentView: View {
    var body: some View {
        let HTMLString =
            """
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width">
            <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
            <script>var formula = document.getElementById('formula');formula.style.color="#FF0000"</script>
            <p id="formula" style="font-size: 35px;">
                      \[A = P(1+r)^t\]
            </p>
            <script src="change-color.js"></script>
            """
        HTMLView(htmlString: HTMLString).frame(width: .infinity, height: 80)
    }
}

Here is the js file:

var formula = document.getElementById('formula');
formula.style.color="#FF0000";

HTMLView:

import SwiftUI
import WebKit

struct HTMLView: UIViewRepresentable {
    
    let htmlString: String
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.scrollView.isScrollEnabled = false
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlString, baseURL: nil)
    }
}

Directories and files:

enter image description here

Advertisement

Answer

Try to add Bundle.main.bundleURL and change the change-color file name to change-color.js.

uiView.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement