对请求使用共享的 WKWebViewCookies [英] Use shared WKWebViewCookies for a request

查看:36
本文介绍了对请求使用共享的 WKWebViewCookies的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有几个不同的 WKWebView,它们都通过一个 WKProcessPool 共享 cookie.

I have a few different WKWebViews inside my project they are all sharing cookies over a single WKProcessPool.

现在我想在 REST API 上发出请求,并且需要将那个 cookie 从那个 WKWebViews 准确地发送到那个 API.有没有办法得到饼干?我得到的一切都是来自 NSHTTPCookieStorage 的 cookie,但它们似乎与我在 WKWebView 中使用的 cookie 并不真正同步.或者甚至有可能发出使用 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) 如果您的 cookie 不是仅用于 HTTP 的,您可以通过在 上评估 JavaScript 命令 document.cookie 来获取它们webView 并将它们用于您的请求.如果它们是 HTTP-only,似乎没有工作方法可以做到这一点.据我所知,没有记录在 WKWebViewNSURLSession 之间同步 cookie 的方法.

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) 另一种方法(如果 cookie 属于 REST API 所属的同一域) - 创建具有相同进程池的背景" webView 并通过此实例对 REST API 执行所有操作 - cookie 将是自动添加(甚至仅支持 HTTP):

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. 您可以设置任何参数(方法/正文/标题/等)来请求和加载它通过 loadRequest:;如果您的 REST API 返回 JSON,您可以使用 JavaScript 命令document.body 获取它;

  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;

获取响应代码有点困难 - 您需要实现webView:decidePolicyForNavigationResponse: 方法WKNavigationDelegatecatch它.

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

此外,您需要记住,您只能执行 1 个请求同时在 webView 中.因此,您可能需要创建一些队列一个接一个执行的请求.

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.

这篇关于对请求使用共享的 WKWebViewCookies的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆