Call JavaScript function from native code in WKWebView

Sophie Alpert picture Sophie Alpert · Jun 5, 2014 · Viewed 67.8k times · Source

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:.

(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.)

Answer

Sophie Alpert picture Sophie Alpert · Jun 15, 2014

(I filed a Radar for this shortly after asking the question here.)

A new method was just added a few days ago (thanks jcesarmobile for pointing it out):

Add -[WKWebView evaluateJavaScript:completionHandler:]
http://trac.webkit.org/changeset/169765

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; 

Docs are available here: https://developer.apple.com/documentation/webkit/wkwebview/1415017-evaluatejavascript.