WKWebView injection Cookie level: ★☆☆ tag: “iOS” “UIWebView injection Cookie” “WKWebView injection Cookie


In the previous article, the author shared the introduction of cookies. In this article, the author will inject cookies and obtain cookies in the response header returned by the server when embedding UIWebView and WKWebView in the sharing native App.

Why inject cookies into UIWebView, WKWebView

The author assumes the following scenarios:

Sometimes you don’t just have a native interface in your App, but you also have an embedded UIWebView, or WKWebView. For example, there’s an App, QiShare, that’s embedded in Jane’s web page. Therefore, for a user who uses traditional Chinese, we can set local to zh-TW in the Cookie when loading the Simple book WebView, so that the user can switch from the original QiShare App to browse the simple book WebView, and still see the traditional content.

In addition, using Jane as an example, when I visited QiShare’s website using WebView, I found that it was in the “followed” state by setting remeber_user_token in the Cookie.

Describe this example in detail

Take the brief introduction to QiShare Cookie as an example: The author used UIWebView to load the Cookie introduction page and set local as zh-TW in the Cookie. However, when loading for the first time, it will not be directly displayed as traditional, I think the reason is the first simple book WebView, simple book server has not returned the corresponding traditional information. However, when THE author opened the other WebView of Jane book for the second time, it still did not show traditional Chinese, which is still a little wonder.

I tried it, and when we opened the QiShare link, we found that the display content was already traditional.

Remember_user_token = remember_user_token = remember_user_token = remember_user_token = remember_user_token QiShare attention status, showing attention. To do this, we need to log in to the WebView of Jane book (on the simulator, if we want to log in to the UIWebView of Jane Book, we can open any article and click “like” to go to the login interface of WebView), and then, There is a remember_user_token inside the Cookie to tell us that the status we care about is remember_user_token.

UIWebView infuses cookies:

The author first uses UIWebView to load QiShare and set the locale in the Cookie to zh-TW, as an example to illustrate UIWebView to inject cookies. The following code can be used to set the locale parameter representing the local language in the Cookie to ‘traditional’ (zh-TW).

    NSDictionary *keyPropertiesLocal = @{
                                    NSHTTPCookieName: @"locale",
                                    NSHTTPCookieValue: @"zh-TW",
                                    NSHTTPCookiePath: @"/",
                                    NSHTTPCookieDomain: @".jianshu.com"
                                    };
                                    
	NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:keyPropertiesLocal];
	
	[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
	
	NSURL *url = [NSURL URLWithString:@"https://www.jianshu.com/p/1174d1dbe650"];
	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	[_webView loadRequest:request];
	
Copy the code

[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie: Set cookies to automatically carry the injected Cookie every time UIWebView is loaded, somewhat global effect.

NSHTTPCookieStorage injects cookies:

The code is as follows:

/ /! Generates an instance of NSHTTPCookie that specifies cookieName cookieValue cookiePath cookieDomain - (NSHTTPCookie *)cookieWithName:(NSString *)name cookieValue:(NSString *)value cookiePath:(NSString *)path cookieDomain:(NSString *)domain { NSDictionary *keyProperties = @{ NSHTTPCookieName: name, NSHTTPCookieValue: value, NSHTTPCookiePath: path, NSHTTPCookieDomain: domain }; NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:keyProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookie];
    return cookie;
}
Copy the code
/ /! Set (generate NSHTTPCookie instance specifying cookieName cookieValue cookiePath cookieDomain) to NSHTTPCookieStorage - (NSHTTPCookie *)setCookieWithName:(NSString *)name cookieValue:(NSString *)value  cookiePath:(NSString *)path cookieDomain:(NSString *)domain {
    
    if(! name || ! value || ! path || ! domain) {return nil;
    }
    NSHTTPCookie *cookie = [self cookieWithName:name cookieValue:value cookiePath:path cookieDomain:domain];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    
    return cookie;
}

Copy the code

The usage is as follows:

    NSURL * url = [NSURL URLWithString:@"https://www.jianshu.com/p/1174d1dbe650"];
    [self setCookieWithName:@"local" cookieValue:@"zh-TW" cookiePath:@"/" cookieDomain:kJianshuDomain];
    [self setCookieWithName:@"QiShareToken" cookieValue:@"QiShareTokenValue" cookiePath:@"/" cookieDomain:kJianshuDomain];
    [self setCookieWithName:@"QiShareKey" cookieValue:@"QiShareValue" cookiePath:@"/" cookieDomain:kJianshuDomain];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [_webView loadRequest:request];
Copy the code

The Demo effect after setting local in Cookie is shown in the following figure. It can be seen that parts of “Followed”, “Latest comments” and “Popular” have been displayed in traditional format.

Use Charles to view the effect of Cookie injection:

WKWebView injection Cookie:

The author uses WKWebView to load the gold digging URL, and WKWebView injects cookies during the loading process. WKWebView sets the following cookies (set a Cookie named QiShareAuth1 with the value of QiShareAuth1; Also set a Cookie named QiShareAuth2 value QiShareAuth2). You can use the following code:

The Cookie is already injected when WKWebView is created

    WKUserContentController *userContentController = [WKUserContentController new];
    NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = 'QiShareAuth1=QiShareAuth1'; document.cookie = 'QiShareAuth2=QiShareAuth2';"];
    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = userContentController;
    
    NSURL *juejinUrl = [NSURL URLWithString:@"https://juejin.cn"];
    NSMutableURLRequest *mJuejinRequest = [[NSMutableURLRequest alloc] initWithURL:juejinUrl];
    // [mJuejinRequest addValue:@"QiShareAuth1=QiShareAuth1; QiShareAuth2=QiShareAuth2" forHTTPHeaderField:@"Cookie"];
    WKWebView *wkWebV  = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    _wkWebView = wkWebV;
   [self.view addSubview:wkWebV];

Copy the code

Still have questions?

When I used Demo QiNetwork to check the effect of using the above code, I thought I had solved the problem, and found that WKWebView did not carry the Cookie we injected when it first loaded the request. Reviewed the relevant information after the blog mentioned before loading request, can use to _wkWebView. Configuration. WebsiteDataStore. HttpCookieStore setting cookies, solve the problem, but I tried, did not achieve the desired effect.

Finally, when the request is loaded for the first time, the author adds cookies required by a request to mJuejinRequest in the case of the above code, and the relevant code is as follows:

[mJuejinRequest addValue:@"QiShareAuth1=QiShareAuth1; QiShareAuth2=QiShareAuth2" forHTTPHeaderField:@"Cookie"];
Copy the code

The above code can also be used to set cookies for a single request. Use Charles to view the effect of Cookie injection:

The Demo:

For more information, see QiNetwork

Refer to study website

  • WKWebView the pit
  • IOS Cookie access look I absolutely enough!!

Xiaobian wechat: You can add and pull into “QiShare Technical Exchange Group”.

QiShare(Simple book) QiShare(digging gold) QiShare(Zhihu) QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat public account)

IOS Runloop iOS Runloop iOS Runloop iOS Runloop iOS Runloop The LLDB command is used to debug iOS