本文是我的学习总结 希望对后来学习这一方面的同学有所帮助
UIWebview与js传值方式有两种
第一种是为js注入对象的方式
//这种方法是给js注入SMJSExportFunction对象实现
- (void)webViewDidFinishLoad:(SMWebView *)webView{
self.context = [webView.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
SMJSExportFunction *exportFunction =[SMJSExportFunctionnew];
exportFunction.delegate=self;
self.context[@"wobridge"]=exportFunction;//wobridge为js对象
}
对应的js中应有wobridge对象接受,注入成功后即可用wobridge调用oc本地方法,本地创建SMJSExportFunction实现JSExport协议
第二种方式 以 JSExport协议关联 native 的方法
- (void)webViewDidFinishLoad:(SMWebView *)webView{
self.context = [webView.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.context.exceptionHandler =
^(JSContext *context, JSValue *exceptionValue)
{
context.exception = exceptionValue;
NSLog(@"%@", exceptionValue);
};
self.context[@"native"] = self;//关联native
//js中调用sumit方法将在此处响应
self.context[@"submit"] =
^(id dic)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:@"ll" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
});
};
}WKWebView传值方式首先需要向js注入TestModel对象,这样js可以通过
window.webkit.messageHandlers.TestModel.postMessage()通知传值
下为添加对象方法
SMScriptMessageDelegate *sDelegate=[[SMScriptMessageDelegatealloc] initWithDelegate:(id)self];
[self.webViewaddScriptMessageHandler:sDelegatename:@"TestModel"];
js给oc传值再此实现方法调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage*)message
关于cache WK不支持NSURLCache,所以无法截取网络连接 替换cache内容
UIWebView截取cache首先需要设置
[NSURLCachesetSharedURLCache:cache]
关于cookie
UIWebView支持NSHTTPCookieStorage可以通过
NSArray *cookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage] cookiesForURL:[NSURLURLWithString:@"www.baidu.com"]];//此处链接应为你的项目ip
for (NSHTTPCookie *cookiein cookies){
NSArray *headeringCookie = [NSHTTPCookiecookiesWithResponseHeaderFields:[NSDictionarydictionaryWithObject:[[NSStringalloc] initWithFormat:@"%@=%@",[cookiename],[cookie value]]forKey:@"Set-Cookie"]forURL:[NSURLURLWithString:@"www.baidu.com"]];
[[NSHTTPCookieStoragesharedHTTPCookieStorage] setCookies:headeringCookieforURL:[NSURLURLWithString:@"www.baidu.com"]mainDocumentURL:nil];
}
来设置cookie需要共用WKWebView如果需要设置cookie 需要通过注入js方法设置实现
[_webViewaddUserScriptWithJS:[NSStringstringWithFormat:@"document.cookie=\'%@\'",[NSStringstringWithFormat:@"JSESSIONID=272173718"]]injectionTime:WKUserScriptInjectionTimeAtDocumentStartforMainFrameOnly:NO];
各个wk之间共用cookie需要共用WKProcessPool这个文件管理池来实现
if ([SMWebviewManagershareManager].processPool) {
configuration.processPool=[SMWebviewManagershareManager].processPool;
}else{
WKProcessPool *processPool=[[WKProcessPoolalloc] init];
[SMWebviewManagershareManager].processPool=processPool;
}
上面是我近段时间学习js与oc交互的总结,一些简单知识,或许对大家有所帮助,详细代码
https://github.com/lixuepeng996/SMWebView