PWKWebView icon indicating copy to clipboard operation
PWKWebView copied to clipboard

load override calls super.load() on 302 request

Open julienbodet opened this issue 6 years ago • 3 comments

First, thanks for this great workaround!

From the override of the load func:

if let Data = data,let Resp = resp {
                    // load data directly for 200 response
                    if #available(iOS 9.0, *) {
                        let _ = self.webViewLoad(data: Data, resp: Resp)
                    } else {
                        // load request again instead of calling loadHTMLString in case of css/js not working
                        let req = self.syncCookies(newRequest)
                        let _ = super.load(req)
                    }
                } else {
                    let req = self.syncCookies(newRequest)
                    let _ = super.load(req)
                }

In case the response is not a 200 but a 302 as an example, you load the new created request by calling the super.load(req) method of the WKWebView. Why don't you call self.load(req) to load this request using the URLSession instance?

Actually by calling super.load(req), cookies returned in the Set-Cookie header field won't be set in the cookie storage by the URLSession.

So the new code would be:

if let Data = data,let Resp = resp {
                    // load data directly for 200 response
                    if #available(iOS 9.0, *) {
                        let _ = self.webViewLoad(data: Data, resp: Resp)
                    } else {
                        // load request again instead of calling loadHTMLString in case of css/js not working
                        let req = self.syncCookies(newRequest)
                        let _ = super.load(req)
                    }
                } else {
                    let _ = self.load(newRequest)
                }

julienbodet avatar Jun 14 '18 21:06 julienbodet

The purpose of this hack workaround is to handle that WKWebview does not accept cookies in 302 response,and the URLSession can help with it.Then all we need to do is sync the cookies from HTTPCookieStorage to WKWebview by setting the cookie header of the URLRequest.

luowenxing avatar Jun 28 '18 07:06 luowenxing

If you want to deal with cookies apart from WKWebview itself,that may cause more problems because it's just a black box.

luowenxing avatar Jun 28 '18 07:06 luowenxing

Yes but what if there is multiple subsequent 302 responses? Actually once you get a 302 response you sync the cookies to HTTPCookieStorage and the new request is loaded by the WKWebview itself instead of the URLSession instance. In case this new request responds with a 302 too, we may lost cookies as we're not syncing them with HTTPCookieStorage. Does this make sense?

julienbodet avatar Jun 28 '18 10:06 julienbodet