1
.
.
.

<script>
    function resizeFont(font_index) {
         var arrFontSize = ["80%", "90%", "100%", "110%", "120%"];
         var x = document.getElementsByTagName("SPAN");
         for (var i = 0; i < x.length; i++) {
             x[i].style.fontSize = arrFontSize[font_index];
         }
    }
</script>

The above function is to adjust the font of the page that shows the contents of the book.

override func viewDidLoad() {
        super.viewDidLoad()

        let webConfiguration = WKWebViewConfiguration()
        let contentController = WKUserContentController()

        contentController.add(self, name: "resizeFont")

        webConfiguration.userContentController = contentController
        webView = WKWebView(frame: self.containerView.frame, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        self.view.addSubview(ebView)
    }


extension SearchWVViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

        if let name = message.name as? String, name == "resizeFont" {

            //code
        }
}

The code above executes a function with no parameters to pass. But how do I execute a function while passing a font_index?

1 Answer 1

1

If you want to execute JS function for WKWebView just use evaluateJavaScript method e.g.

let fontIndex = 1
webView.evaluateJavaScript("resizeFont(\(fontIndex))")

Use userContentController(:) if you want to receive messages from JS running in a webpage. But in your case, if you want to just execute some JS function in a webpage, you don't need to use WKUserContentController and WKScriptMessageHandler, just use evaluateJavaScript method.

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.