We often encounter scenarios where we need to inject cookies into WKWebView from the outside.
There are several specific schemes, generally speaking, the choice needs to be made in combination with the actual scene.
Here is a description of an actual scenario in a project I’ve encountered.
The background is that for some reason, we need to transform a piece of JS logic into Native logic.
The JS logic is to first request an API, and the response header of the API will have a Set-Cookie field and return a jump link.
After that, JS will jump to this link, because the two links are in the same domain, so no additional processing is required.
The logic of Native is outside the webview, requesting the API, and manually processing the Set-Cookie and jump logic in the response header. The question is how to handle Set-Cookie more securely.
Here is the direct conclusion.
The solution we adopt is to inject Cookies in two ways at the same time.
Add Set-Cookie content in the request of loadRequest: to solve the Cookies required by SSR (Server-Side Rendering).
Add the userScript that injects Cookies in WKWebView’s configuration.userContentController. In order to solve the problem of using cookies in the current page and in the secondary page.