Use shared WKWebViewCookies for a request

99封情书 提交于 2019-12-10 22:31:03

问题


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):

  1. 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 command document.body to get it;

  2. Getting response code a little bit harder - you need to implement webView:decidePolicyForNavigationResponse: method of WKNavigationDelegate and catch it.

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!