WKWebView cookie 容错

xiaoxiao2025-04-26  9

最近iOS项目中,需要在app端设置cookie,然后web取cookie验证用户身份,但是cookie中的一些字段无论如何也去不到,二app设置断点后却真实的看到了我“正确的”设置了cookie。因为问题还发生在一些特定的手机上,所以我们开始比较这些手机之间的区别。

大家都知道,cookie的格式大致如下

document.cookie = 'key1=value1';document.cookie = 'key2=value2'

附上一段我生成cookie的代码以及cookie示例

WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init]; // 设置偏好设置 webConfig.preferences = [[WKPreferences alloc] init]; // 默认为0 webConfig.preferences.minimumFontSize = 10; webConfig.processPool = [[WKProcessPool alloc] init]; // 将所有cookie以document.cookie = 'key=value';形式进行拼接 NSString *cookieValue = [HXURLConfigure commonCookieResult]; // 加cookie给h5识别,表明在ios端打开该地址 WKUserContentController* userContentController = WKUserContentController.new; WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: cookieValue injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; [userContentController addUserScript:cookieScript]; webConfig.userContentController = userContentController; _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfig]; /** 样式如下 document.cookie = 'access_token=1234'; document.cookie = 'appid=1234'; document.cookie = 'device_name=iPhone XS'; document.cookie = 'device_specification=x86_64'; document.cookie = 'device_token=12345'; document.cookie = 'deviceid=66E3BFD9-9C2C'; document.cookie = 'system_name=iOS'; document.cookie = 'system_version=13.0'; document.cookie = 'timestamp=1640778495'; document.cookie = 'version=12.10.0'; document.cookie = 'sign=shsjufoisdiu23fisudofsfuosdf'; */

可以看到,每个cookie是由单引号引起来的,试想,如果value或者key中出现了单引号:'    ,那么整个cookieString就被这个单引号提前截断了,他后面的其他数据就会丢失。在上面的cookie示例中,如果device_name=GP'iPhone  x,那么后面的device_specification、device_token等等就都无效了,这样就直接导致js在获取cookie里面的某些参数时,获取失败,影响判断。比如说我们想给版本》2.0以及2.0之后的app加一个分享功能,那么显然,device_name包含单引号后,version是取不到的,当时编码的我甚至怀疑人生了。

发现问题后,我做了判断,去掉了value中的单引号,问题搞定。

转载请注明原文地址: https://www.6miu.com/read-5029207.html

最新回复(0)