有關(guān)WKWebView處理cookie問(wèn)題技俐,又多次測(cè)試堕花,發(fā)現(xiàn)并不需要在 初識(shí)WKWebView那么麻煩哮内,有更簡(jiǎn)便的方法祈噪,實(shí)例代碼如下:
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所有值傳過(guò)去
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;
}
注意點(diǎn):
1泽铛,通過(guò)WKUserScript
2,設(shè)置cookie格式