I would like to run some JavaScript code on new data each second, which I want to transmit from the iOS side to the web view side.
Let's say I wanted to change the color of the web view back ground once every second. I have code looking somewhat like this:
HTML (htmlDocFileName):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body style="background-color:#EDF2F7;">
<script>
function changeBackgroundColor(colorText) {
document.body.style.background = colorText;
}
</script>
</body>
</html>
Swift view:
import SwiftUI
struct View: View {
var body: some View {
RepresentedView()
}
}
Swift represented view:
import UIKit
import SwiftUI
import WebKit
struct RepresentedView: UIViewRepresentable {
typealias UIViewType = WKWebView
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
let url = url = Bundle.main.url(forResource: "htmlDocFileName", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
}
func updateUIView(_ uiView: WKWebView, context: Context) {
uiView.evaluateJavaScript("changeBackgroundColor('red')", completionHandler: nil)
}
}
When I run the code the web view is presented, but the JavaScript function is not executed.
I am able to evaluate JavaScript by using a WKUserScript instead, but with this method I am unable to run the JavaScript function more than once, which is what I want to do.
I have only tested this in Xcode's preview mode, as I am unable to test a running app container.