有关WKWebView处理cookie问题,又多次测试,发现并不需要在 初识WKWebView那么麻烦,有更简便的方法,实例代码如下:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource:[self obainSettingCookieJs]
injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
userContentController;
- (NSString *)obainSettingCookieJs{
NSString *JSFuncString =
@"function setCookie(name,value,expires)\
{\
var oDate=new Date();\
oDate.setTime(oDate.getTime()+(expires*24*3600*1000));\
document.cookie=name+'='+value+';expires='+oDate+';path=/';\
}\
function getCookie(name)\
{\
var arr = document.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));\
if(arr != null) {return unescape(arr[2]); } else { return null;}\
}\
function delCookie(name)\
{\
var exp = new Date();\
exp.setTime(exp.getTime() - 1);\
var cval=getCookie(name);\
if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
}";
//拼凑js字符串
//取出 JSESSIONID uid token
// [SettingBaseTool deleteDatasByKey:jessionString];
// [SettingBaseTool deleteDatasByKey:uidString];
// [SettingBaseTool deleteDatasByKey:tokenString];
NSMutableString *JSCookieString = JSFuncString.mutableCopy;
//把cookie所有值传过去
NSMutableArray *allCookiesArray = [SettingBaseTool queryAllCookies];
for (NSString *cookiesString in allCookiesArray) {
NSArray *cookiesArray = [cookiesString componentsSeparatedByString:kCookieConnectString];
if ([cookiesArray isNotEmpty]&&(cookiesArray.count == 2)) {
NSString *keyString = cookiesArray[0];
NSString *valueString = cookiesArray[1];
if ([valueString isNotEmpty]) {
NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 15);", keyString, valueString];
[JSCookieString appendString:excuteJSString];
}
}
}
return JSCookieString;
}
注意点:
1,通过WKUserScript
2,设置cookie格式
网友评论