Marc Rasmussen
Marc Rasmussen

Reputation: 20565

WkWebview local site Access Origin

enter image description here

i have the following application as, the folder structure is as the picture above.

Then i load this index.html in the following way:

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate{
      var webView: WKWebView!

     override func loadView() {
         webView = WKWebView()
         view = webView
     }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true
        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "iosbuild")!
        webView.loadFileURL(url, allowingReadAccessTo: url)

        
    }
}

When inspecting this in my Safari browser I get an access-origin error:

Origin null is not allowed by Access-Control-Allow-Origin.

What have I done wrong? or how I might change the URL to allow the load of my assets / scripts?

Upvotes: 1

Views: 3510

Answers (1)

Shawn Frank
Shawn Frank

Reputation: 5213

I tried the exact same code with your folder structure and this worked for me so I think this error originates from the html content.

Try and see if any of these help you:

Set he allow read access on the directory

// I added
let directoryURL = Bundle.main.resourceURL!.appendingPathComponent("iosbuild")

// your code
let url = Bundle.main.url(forResource: "index",
                          withExtension: "html",
                          subdirectory: "iosbuild")!

// changed read access
webView.loadFileURL(url, allowingReadAccessTo: directoryURL)

This could be CORS related, so add a webview configuration

// Configure this before instantiating web views
// Worked for me in the past with CORS errors
let configs = WKWebViewConfiguration()
configs.setValue(true, forKey: "_allowUniversalAccessFromFileURLs")

let webView = WKWebView(frame: view.bounds, configuration: configs)
self.view.addSubview(webView)

// rest of your delegate set up
webView.navigationDelegate = self
webView.uiDelegate = self
webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = true

// your code
let url = Bundle.main.url(forResource: "index",
                          withExtension: "html",
                          subdirectory: "iosbuild")!

// this is back to your own code but if it doesn't work
// you can try allowing the read access on the directory like before
webView.loadFileURL(url, allowingReadAccessTo: url)

Give these a go and see if this gives you any luck

Upvotes: 2

Related Questions