1. 程式人生 > >WKWebView JS互動

WKWebView JS互動

OC與js互動,主要是先知道,誰呼叫誰的方法,誰實現;

具體實現如下:
#import <JavaScriptCore/JavaScriptCore.h>
@interface JumpWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;

—(void)viewDidLoad {
[super viewDidLoad];
// 用於初始化Web檢視的配置副本。
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.userContentController = [[WKUserContentController alloc] init];
config.processPool = [[WKProcessPool alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
configuration:config];
self.webView.UIDelegate = self;
self.webView.navigationDelegate =self;
[self.view addSubview:self.webView];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];

// 新增js呼叫oc的方法名
[config.userContentController addScriptMessageHandler:self name:@“gobackForhtml”];
}
#pragma mark - WKScriptMessageHandler
**—(void)userContentController:(WKUserContentController )userContentController didReceiveScriptMessage:(WKScriptMessage )message {
// 實現js呼叫OC的方法
if ([message.name

isEqualToString:@“gobackForhtml”]) {
NSLog(@"%@", message.body);
// OC實現方法
}
}
#pragma mark --------- WKNavigationDelegate --------------
**—(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation )navigation
{
// OC呼叫js的方法
NSString * jsStr =[NSString stringWithFormat:@“init(’%@’)”,appString(AppInfoUserToken)];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
// js返回值

DLog(@"%@====%@",result,error)
}];
}