美文网首页
iOS使用WKWebView向js传值

iOS使用WKWebView向js传值

作者: 贝勒老爷 | 来源:发表于2019-05-15 09:55 被阅读0次

    通常WKWebView传值,使用evaluateJavaScript调用js方法即可.

    NSString * jsStr = [NSString stringWithFormat:@"someMethod('%@')", data];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    
    }];
    

    项目前端使用Vue,需要在mounted(){}的方法内获取iOS端本地储存的一些数据发起请求.
    iOS端可以在js加载前,把数据转成JSON字符串,加到js window下的对象,前端再去读取此对象.具体实现如下:

    - (void)wkConfiguration
    {
        self.configuration = [[WKWebViewConfiguration alloc] init];
        self.configuration.userContentController = [WKUserContentController new];
        
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        self.configuration.preferences = preferences;
        
        NSMutableDictionary *dic = [NSMutableDictionary new];
        dic[@"username"] = [UserInfoTool username];
        dic[@"token"] = [UserInfoTool token];
        dic[@"avatar"] = [UserInfoTool avatar];
    
        NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:(NSJSONWritingPrettyPrinted) error:nil];
    
        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSString *js = [NSString stringWithFormat:@"window.iOSInfo = %@", jsonStr];
        
        WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES];
        [self.configuration.userContentController addUserScript:script];
    }
    
    // 添加配置
    _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:self.configuration];
    

    前端读取如下:

    mounted(){
       let iOSInfo = JSON.parse(JSON.stringify(window.iOSInfo));
       // iOSInfo. username  iOSInfo. token iOSInfo.avatar
    }
    

    相关文章

      网友评论

          本文标题:iOS使用WKWebView向js传值

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