gualtierofrigerio / CustomSchemeHandler

Project to demonstrate the usage of WKURLSchemeHandler to serve local assets or data to a WKWebView
10 stars 1 forks source link

Can't get response due to Access-Control-Allow-Origin #1

Open JulianSong opened 1 year ago

JulianSong commented 1 year ago

According to cors proxy xhr request can't get response without set Access-Control-Allow-Origin header in HTTPURLResponse.

gualtierofrigerio commented 1 year ago

Not sure I understand the problem, are you getting this error in Javascript in your page? Do you have an example to show?

JulianSong commented 1 year ago
class JSONURLSchemaHandler:NSObject, WKURLSchemeHandler {
    func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {#imageLiteral(resourceName: "simulator_screenshot_36902A1E-0748-4CF8-8822-A28369D1A849.png")
        guard
            let url = urlSchemeTask.request.url,
            let data = "{\"status\":\"ok\"}".data(using: .utf8),
            let originHost = urlSchemeTask.request.allHTTPHeaderFields?["Origin"],
            let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "1.1", headerFields: [
                "Access-Control-Allow-Origin":originHost,
                "Content-type":"application/json; charset=UTF-8"
            ])
        else {
            return
        }

        urlSchemeTask.didReceive(response)
        urlSchemeTask.didReceive(data)
        urlSchemeTask.didFinish()
    }

    func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {

    }
}
<html>

<body>
    <h1>跨域测试</h1>
    <img src="appassets://img/IMG_8230.PNG" style="width: 100%;"/>
    <script type="application/javascript">
        var localRequest = "applocal://handle"
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                alert(xhr.responseText);
            }
        }
        try {
            xhr.open("GET", localRequest, true);
            xhr.send();
        }
        catch (ex) {
            alert(ex.message);
        }
    </script>
</body>

</html>

JSONURLSchemaHandler is a json WKURLSchemeHandler which response json data to html page. If I don't set Access-Control-Allow-Origi in response header the js XMLHttpRequest will get an error like this

image

10.67.84.108:5500 is my local nginx server address.

gualtierofrigerio commented 1 year ago

You can also try this

let configuration = WKWebViewConfiguration()
configuration.setValue(true, forKey: "allowUniversalAccessFromFileURLs")

webView = WKWebView(frame: frame, configuration: configuration)

I mentioned it in my blog post, so I guess I had a similar error at some point and found this solution. To be honest I'm not particularly fond of it since I'm setting a key as a String to the configuration and it may change in future versions of iOS, but it was more convenient than setting the header every time I guess