问题
I have a few different WKWebViews inside my project they are all sharing cookies over a single WKProcessPool.
Now I want to make a request on a REST API and need to send exactly that cookies from that WKWebViews to that API. Is there a way to get the cookies? Everything I get are the cookies from the NSHTTPCookieStorage
but they seem not really in sync with the cookies I use in the WKWebView. Or is there even the possibility to make a request that uses the WKProcessPool too?
回答1:
1) If your cookies are not HTTP-only, you can get them by evaluating JavaScript command document.cookie
on webView
and use them for your request.
If they are HTTP-only, it seems that there is no working method to do this.
There is no documented way to sync cookies between WKWebView
and NSURLSession
as far as I know.
2) Another approach (if cookies belong to same domain which REST API belongs) - create "background" webView
with same process pool and perform all operations to REST API via this instance - cookies will be added automatically (even HTTP-only):
You can set any params (method/body/headers/etc) to request and load it via
loadRequest:
; If your REST API returns JSON, you can use JavaScript commanddocument.body
to get it;Getting response code a little bit harder - you need to implement
webView:decidePolicyForNavigationResponse:
method ofWKNavigationDelegate
and catch it.Also, you need to keep in mind that you can perform only 1 request in
webView
simultaneously. So, you may need to create some queue of requests that will be performed one after another.
来源:https://stackoverflow.com/questions/39076163/use-shared-wkwebviewcookies-for-a-request