从WKWebView中的本机代码调用JavaScript函数 [英] Call JavaScript function from native code in WKWebView
问题描述
在iOS 8中使用WKWebView,如何从本机端运行JavaScript函数或以其他方式从本机端到JavaScript进行通信?似乎没有类似于UIWebView的 stringByEvaluatingJavaScriptFromString的方法:
。
Using a WKWebView in iOS 8, how can I run a JavaScript function from the native side or otherwise communicate from the native side to JavaScript? There doesn't appear to be a method akin to UIWebView's stringByEvaluatingJavaScriptFromString:
.
(我可以使用 - addScriptMessageHandler:name:
在 configuration.userContentController
对象上,允许从JS到本地的通信,但我正在寻找相反的方向。)
(I can use - addScriptMessageHandler:name:
on the configuration.userContentController
object to allow communication from JS to native, but I'm looking for the opposite direction.)
推荐答案
(我在这里提出问题之后不久就提交了雷达。)
(I filed a Radar for this shortly after asking the question here.)
几天前刚刚添加了一种新方法(感谢jcesarmobile指出):
A new method was just added a few days ago (thanks jcesarmobile for pointing it out):
添加
- [WKWebView evaluateJavaScript:completionHandler:]
http://trac.webkit.org/changeset/169765
该方法适用于iOS 8 beta 3及以上。这是新方法签名:
The method is available in iOS 8 beta 3 and up. Here's the new method signature:
/* @abstract Evaluates the given JavaScript string.
@param javaScriptString The JavaScript string to evaluate.
@param completionHandler A block to invoke when script evaluation completes
or fails.
@discussion The completionHandler is passed the result of the script evaluation
or an error.
*/
- (void)evaluateJavaScript:(NSString *)javaScriptString
completionHandler:(void (^)(id, NSError *))completionHandler;
这里有文档: https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript 。
这篇关于从WKWebView中的本机代码调用JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!