关于WKWebView 无法获取Cookie的解决方法以及去除长
2017-03-20 本文已影响0人
Lukiwen
由于WKWebView实例不会把Cookie存入到App标准的的Cookie容器(HTTPCookieStorage)中, WKWebView拥有自己的私有存储.
因为 NSURLSession/NSURLConnection等网络请求使用HTTPCookieStorage进行访问Cookie,所以不能访问WKWebView的Cookie,现象就是WKWebView存了Cookie,其他的网络类如NSURLSession/NSURLConnection却看不到. 同时WKWebView也不会读取存储在HTTPCookieStorage中的Cookie.
要解决这一问题,通过JS的方式注入Cookie是对于我们目前的代码来说是最合适也是最方便的. 因为我们已经有了注入到HTTPCookieStorage的代码, 那么只需要把这些Cookie转化成JS并且注入到WKWebView里面就可以了。
fileprivate class func getJSCookiesString(_ cookies: [HTTPCookie]) -> String {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.string(from: date)); "
}
if (cookie.isSecure) {
result += "secure; "
}
result += "'; "
}
return result
}
注入的方法就是在每次initWkWebView的时候, 使用下面的config就可以了:
public class func wkWebViewConfig() -> WKWebViewConfiguration {
let userContentController = WKUserContentController()
if let cookies = HTTPCookieStorage.shared.cookies {
let script = getJSCookiesString(cookies)
let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
}
//禁止长按弹出 UIMenuController 相关
//禁止选择 css 配置相关
let css = "('body{-webkit-user-select:none;-webkit-user-drag:none;}')"
//css 选中样式取消
let javaScript = NSMutableString()
javaScript.append("var style = document.createElement('style');")
javaScript.append("style.type = 'text/css';")
javaScript.append("var cssContent = document.createTextNode\(css);")
javaScript.append("style.appendChild(cssContent);")
javaScript.append("document.body.appendChild(style);")
javaScript.append("document.documentElement.style.webkitUserSelect='none';")//禁止选择
javaScript.append("document.documentElement.style.webkitTouchCallout='none';")//禁止长按
let noneSelectScript = WKUserScript.init(source: javaScript as String, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(noneSelectScript)
let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
return webViewConfig
}
public class func getJSCookiesString() -> String? {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return nil
}
return getJSCookiesString(cookies)
}
使用如下:
let config = CommonMethod.wkWebViewConfig()
var wkWebView = WKWebView.init(frame: CGRect(x:0,y:0,width:SCREEN_WIDTH,height:SCREEN_HEIGHT), configuration: config)