iOS使用WKWebView向js传值

2019-05-15  本文已影响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
}
上一篇下一篇

猜你喜欢

热点阅读