【问题标题】:WkWebview local site Access OriginwkWebview 本地站点访问来源
【发布时间】:2022-01-30 00:03:51
【问题描述】:

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

然后我通过以下方式加载这个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 以允许加载我的资产/脚本?

【问题讨论】:

    标签: ios swift cors


    【解决方案1】:

    我用你的文件夹结构尝试了完全相同的代码,这对我有用,所以我认为这个错误源于 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)
    

    试一试,看看这是否能给你带来好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2015-04-26
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多