WKWebView -> evaluateJavaScript
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
[webView evaluateJavaScript:@"document.title" completionHandler:^(NSString * _Nullable title, NSError * _Nullable error) {
self.navigationItem.title = title;
}];
}
UIWebView -> stringByEvaluatingJavaScriptFromString
- (void)webViewDidFinishLoad:(UIWebView *)webView{
self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
WKWebView可以通过category方法实现stringByEvaluatingJavaScriptFromString,代码如下
@interface WKWebView(SynchronousEvaluateJavaScript)
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
@end
@implementation WKWebView(SynchronousEvaluateJavaScript)
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
{
__block NSString *resultString = nil;
__block BOOL finished = NO;
[self evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
if (error == nil) {
if (result != nil) {
resultString = [NSString stringWithFormat:@"%@", result];
}
} else {
NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
}
finished = YES;
}];
while (!finished)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return resultString;
}
@end
//具体使用
NSString *userAgent = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"userAgent: %@", userAgent);
JSContext -> evaluateScript
只有UIWebView可以拿到JSContext,WKWebView不能
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//获取到JS的context
JSContext *jsContext = [self.webView_1 valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//设置JS执行报错捕获
[jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
NSLog(@"%@", exception);
}];
JSValue *value = [jsContext evaluateScript:@"document.title"];
self.navigationItem.title = value.toString;
}