WKWebView? JS交互的基本步驟:
1:創(chuàng)建WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
2:創(chuàng)建WKUserContentController *userContentController = [[WKUserContentController alloc] init];
3:[userContentController addScriptMessageHandler:self name:@"functionGetUserInfo(JS中的函數(shù)名)"];
4: configuration.userContentController = userContentController;
5:創(chuàng)建 self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
6:監(jiān)聽WKScriptMessageHandler中的 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message方法,其中message.name可以的到函數(shù)名。
7:如果要將本地的數(shù)據(jù)傳輸給webView 則調(diào)用[self.webView evaluateJavaScript:[NSString stringWithFormat:@"hx.callback('%@');",dataStr] completionHandler:^(id _Nullable result, NSError * _Nullable error) {JWNSLog(@"%@", error);}]; 其中dataStr是要傳輸?shù)膉son字符串。
8:dealloc 中remove掉之前的方法。[self.userContentController removeScriptMessageHandlerForName:@"functionGetUserInfo(JS中的函數(shù)名)"];
UIWebView? JS交互基本步驟:
1:在webViewDidFinishLoad方法中創(chuàng)建JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
2:創(chuàng)建具體的方法
context[@"functionPay(JS中函數(shù)名)"] = ^() {
??????? NSArray *args = [JSContext currentArguments];
? ? ? ? NSMutableArray *webPayArray = [NSMutableArray array];//webpayArray中儲存的傳遞過來的所有數(shù)據(jù)
? ? ? ? for (JSValue *jsVal in args) {
??????????????? [webPayArray addObject:jsVal.toString];
? ? ? ? }
? };
3:如果要向JS中傳遞數(shù)據(jù)? [weakSelf.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"hx.callback('%@');",dataStr]];//dataStr為json字符串