美文网首页我爱编程
IOS JS交互的方法

IOS JS交互的方法

作者: J_W探索者 | 来源:发表于2018-06-07 10:38 被阅读0次

    WKWebView  JS交互的基本步骤:

    1:创建WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

    2:创建WKUserContentController *userContentController = [[WKUserContentController alloc] init];

    3:[userContentController addScriptMessageHandler:self name:@"functionGetUserInfo(JS中的函数名)"];

    4: configuration.userContentController = userContentController;

    5:创建 self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

    6:监听WKScriptMessageHandler中的 - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message方法,其中message.name可以的到函数名。

    7:如果要将本地的数据传输给webView 则调用[self.webView evaluateJavaScript:[NSString stringWithFormat:@"hx.callback('%@');",dataStr] completionHandler:^(id _Nullable result, NSError * _Nullable error) {JWNSLog(@"%@", error);}]; 其中dataStr是要传输的json字符串。

    8:dealloc 中remove掉之前的方法。[self.userContentController removeScriptMessageHandlerForName:@"functionGetUserInfo(JS中的函数名)"];

    UIWebView  JS交互基本步骤:

    1:在webViewDidFinishLoad方法中创建JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    2:创建具体的方法

    context[@"functionPay(JS中函数名)"] = ^() {

            NSArray *args = [JSContext currentArguments];

            NSMutableArray *webPayArray = [NSMutableArray array];//webpayArray中储存的传递过来的所有数据

            for (JSValue *jsVal in args) {

                    [webPayArray addObject:jsVal.toString];

            }

      };

    3:如果要向JS中传递数据  [weakSelf.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"hx.callback('%@');",dataStr]];//dataStr为json字符串

    相关文章

      网友评论

        本文标题:IOS JS交互的方法

        本文链接:https://www.haomeiwen.com/subject/wuiwsftx.html