Saturday, September 22, 2018

Using WKURLSchemeHandler for wkwebview cross domain requests

One issue to limit ios app to use WKWebView is cross domain requests, basically html file loaded from local file system cannot send requests to remote server, and vice versa, html file loaded from remote server cannot load js files from local file system.

Apple introduced WKURLSchemeHandler in iOS 11 to solve this issue, however, it still has some problem:
1. only custom scheme can be handled by WKURLSchemeHandler, so well-known scheme, such as http, https cannot be registered and handled by WKURLSchemeHandler.

2. in order to let WKURLSchemeHandler to handle xmlhttprequest, the root html file must also be loaded by the same scheme. If the root html is loaded by scheme of file://, http:// or https://, then calling xmlhttprequest from javascript with custom scheme like myscheme:// does not work with the registered WKURLSchemeHandler.

3. Due to item 2, the only option left is always loading the root html file using custom scheme. When the root html file is loaded using custom scheme, such as myscheme://, then the testing shows the <script> element can load javascript file from any remote servers using https:// or http:// scheme. However, when javascript sends xmlhttprequest to a remote server using http:// or https:// scheme, the request will fail due to the cross domain limitation, as from wkwebview's point of view, those requests are from different schemes.

In order to solve the issue 3, one option is, after loading the root html using the custom scheme, then intercepting and override all xmlhttprequests in javascript side. So for all regular schemes, such as file://, https://, http://, always prefix "wk", so they will become wkfile://, wkhttp://, wkhttps://. Finally using WKURLSchemeHandler to register all the custom schemes used by the app, and then in the custom handler, either loading the content from local file system, or from remote server using NSURLSession.

Another option is customizing the web server's response if you have control over it. So that it can set Access-Control-Allow-Origin header in response to allow custom scheme and origin, although I have not verified that in testing. (To be updated later)




No comments:

Post a Comment