安卓当时做的时候,没有遇到怪事,iOS遇到了一点小麻烦,我会在iOS部分写出来。
废话不说,直接进入正题。
Android (WebView)
伪码如下:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(mUrl,"key="+ value);
if(Build.VERSION.SDK_INT<21) {
CookieSyncManager.getInstance().sync();
}else{
CookieManager.getInstance().flush();
}
mWbView.loadUrl(mUrl);
iOS (WKWebView)
NSURL* url = [[NSURLalloc]initWithString:tmpUrl];
_request= [NSMutableURLRequestrequestWithURL:url];
NSDictionary* properties = [NSDictionarydictionaryWithObjectsAndKeys:
您的域名,NSHTTPCookieDomain,
@"/",NSHTTPCookiePath,
您想共享数据的key,NSHTTPCookieName,
您想共享的数据内容,NSHTTPCookieValue,
nil];
NSHTTPCookie* cookie = [NSHTTPCookiecookieWithProperties:properties];
[[NSHTTPCookieStoragesharedHTTPCookieStorage]setCookie:cookie];
NSArray* cookies = [NSArrayarrayWithObjects: cookie,nil];
NSDictionary* headers = [NSHTTPCookierequestHeaderFieldsWithCookies:cookies];
[_request setAllHTTPHeaderFields:headers];
}
[_wkWebview loadRequest:_request];
注:以上代码写完后,服务器后台可以获取到cookie ,PHP通过$_COOKIE["key"];是可以获取到您想共享的数据,但JS通过jquery $.cookie('key')是获取不到的。Goon Baby!
iOS为了让JS获取到cookie
方法1 JS注入
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation {
[_wkWebview evaluateJavaScript:[ @"document.cookie='key=value']completionHandler:^(idresult,NSError*error) {
}];
}
缺陷:JS在window.onload后依然获取不到,但再后续执行比如<a> onclick 的 function时是可以获取到的。由于我在项目中使用了Vue,需要在onload后获取数据进行通信,我继续死磕。
方法2
NSString* cookie =@"document.cookie = 'key=value";
WKUserContentController* userContentController =WKUserContentController.new;
WKUserScript* cookieScript = [[WKUserScript alloc] initWithSource:cookie
injectionTime:WKUserScriptInjectionTimeAtDocumentStartforMainFrameOnly:NO];
[userContentControlleraddUserScript:cookieScript];
webViewConfig.userContentController= userContentController;
_wkWebview= [[WKWebView alloc] initWithFrame:self.view.frameconfiguration:webViewConfig];
通过以上过程,客户端和PHP、JS通过cookie完美的可以一起玩耍了。