如何让 WKWebView.evaluateJavaScript 在函数调用中返回数据 [英] How do I get WKWebView.evaluateJavaScript to return data in a function call

查看:46
本文介绍了如何让 WKWebView.evaluateJavaScript 在函数调用中返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一些 WKWebView 解析例程.我试图通过检查它的 document.title 来验证我是否已正确导航到页面.我编写了一个函数来完成这项工作,但我似乎无法弄清楚如何从函数返回 HTML 数据或在函数中进行评估并返回 BOOL.我知道我在这里进行异步调用,但不确定如何等待该调用结束并从我的函数调用中反馈响应.

I'm working on some WKWebView parsing routines. I'm trying to validate that I've navigated to a page properly by checking it's document.title. I wrote a function to do this work, but I can't seem to figure out how to return the HTML data from the function or do the evaluation in the function and return a BOOL. I know I'm doing an async call here, but not sure how to wait for that call to end and feed the response back from my function call.

这是我的功能:

func checkTitle (forWebView webView: WKWebView, title: String) -> String{


webView.evaluateJavaScript("document.title", completionHandler: { (innerHTML, error ) in
    let titleString = innerHTML as? String

    return (titleString)

})

这会引发编译器错误.我试图在调用之外声明变量,然后分配并返回它,但它尝试在异步调用完成之前执行该变量.

This throws a compiler error. I've tried to declare the variable outside the call and then assign and return it after, but it tries to execute that before the async call is complete.

推荐答案

你应该使用一个完成处理程序,像这样:

you should use a completion handler, something like this:

func checkTitle (forWebView webView: WKWebView, title: String, completion: @escaping (_ titleString: String?) -> Void) {

   webView.evaluateJavaScript("document.title", completionHandler: { (innerHTML, error ) in

        // Logic here
        completion(innerHTML as? String)  
    })
}

这篇关于如何让 WKWebView.evaluateJavaScript 在函数调用中返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆