UIWebView or WKWebkit for JavaScript?
I want to load the requested webpage and access the DOM elements in order to return a value from one of the nodes. I have JavaScript that does this. The question is the best way to get the value back to my application. I can see that UIWebView has the function
stringByEvaluatingJavaScriptFromString
and WKWebKit has the function
func evaluateJavaScript (javaScriptString: String !, completeHandler: ((AnyObject !, NSError!) → Void)!
Well, what's the main difference between the two, and which is better and why for my use case?
source to share
In general, WKWebView differs from UIWebView in several ways.
- It uses the same Javascript engine that Safari uses, so it speeds up significantly when evaluating Javascript (it only uses time compilation to compile your script machine code before running it).
- It is only supported on iOS8 and up, so it won't work on older platforms.
- It runs in a separate process, so a glitch in the WKWebView code will not delete your entire application.
To answer your specific question, the UIWebView is stringByEvaluatingJavaScriptFromString
blocking your application while waiting for your code to run and is therefore synchronous. In contrast, because the WKWebView code runs in a different process, you must interact with it asynchronously; you submit your request to run Javascript in the WebKit process, and your completion handler is triggered when the JavaScript evaluation is complete and the results are ready. Meanwhile, the thread that called evaluateJavaScript
will continue to execute other code.
source to share