提问人:Chaithra 提问时间:11/6/2023 最后编辑:HangarRashChaithra 更新时间:11/7/2023 访问量:55
无法在 WKWebview 的请求标头中设置 Origin
Not able to set Origin in request header in WKWebview
问:
我有一个 iOS 应用程序,它以 WKWebView 为中心,使用 loadFileURL 加载本地 Web 资产。WKWebView 通过 HTTPS 与后端 API 通信。我们在后端进行了一些更改,因此我们需要为请求标头的来源发送一些特定于应用程序的值。如果我的案例值被某个默认值替换为 file://。我在加载应用程序时遇到 CORS 问题。
是否可以将 WKWebView 的来源更改为 xyz 以避免浏览器查询 API?
let config = WKWebViewConfiguration()
config.setValue(true, forKey: "allowUniversalAccessFromFileURLs")
webView = WKWebView(frame: view.frame, configuration: config)
view.addSubview(webView)
if let htmlPath = Bundle.main.path(forResource: "index", ofType: "html") {
let htmlURL = URL(fileURLWithPath: htmlPath)
var request = URLRequest(url: htmlURL)
webView.load(request)
}
答:
0赞
Imran
11/6/2023
#1
您需要使用自定义 URLRequest 并将该请求加载到 WKWebView 中。
import WebKit
// Create a WKWebView
let webView = WKWebView()
// Create a custom URLRequest
if let url = URL(string: "https://example.com") {
var request = URLRequest(url: url)
// Set the 'Origin' header in the request
request.setValue("https://your-origin-url.com", forHTTPHeaderField: "Origin")
// Load the custom request in the WKWebView
webView.load(request)
}
评论
0赞
Chaithra
11/7/2023
我想从我的捆绑资源加载索引.html文件。我不想加载远程服务器 URL。
评论