美文网首页
再会WKWebView

再会WKWebView

作者: 奶茶007 | 来源:发表于2016-12-14 17:17 被阅读20次

    有关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格式

    相关文章

      网友评论

          本文标题:再会WKWebView

          本文链接:https://www.haomeiwen.com/subject/wvoimttx.html