2

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.

1 Answer 1

1

The problem is with the preview. The preview in Xcode is unable to run the JavaScript provided to the evaluateJavaScript() method.

The above code should work in a running app on a device or in a simulator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.