WkWebview本地站点访问源

WkWebview local site Access Origin

我有如下应用,文件夹结构如上图

然后我按以下方式加载此 index.html

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)

        
    }
}

在我的 Safari 浏览器中检查时,我收到 access-origin 错误:

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

我做错了什么?或者我如何更改 URL 以允许加载我的资产/脚本?

我用你的文件夹结构尝试了完全相同的代码,这对我有用,所以我认为这个错误源于 html 内容。

尝试看看这些是否对您有帮助:

设置允许读取目录

// 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)

这可能与CORS相关,所以添加一个webview配置

// 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)

试试这些,看看这是否会给您带来好运