问题
I created a local HTML file in my iOS app written in swift. The HTML file is loaded into a WKWebView as follows:
let url = Bundle(identifier: myIdentifier).url(forResource: "localHtmlFile", withExtension: "html")
let htmlFormatString = try String(contentsOf: url)
loadHTMLString(string: htmlFormatString, baseURL: nil)
The HTML page contains an iframe which I expect to load an external page:
<div>Test</div>
<iframe src="https://www.somepage.com"></iframe>
The local HTML file is loaded successfully, as I can see the Test
text in the div. The iframe is also created, but empty. If I debug with Safari Developer Tools, there is just an empty html page, but nothing loaded. Also, a network request to the url is not performed at all.
But if I insert an external JavaScript file with <script src="https://url-to-some-js">
, the JS code will be loaded successfully, so there are no network issues. Also, if I load the url directly with webView.load(URLRequest(url: url))
, it's working fine. Only within an iframe, it's not working.
How can I make iframes to external resources working in iOS WKWebView? Is this blocked by iOS at all or do I have to configure something else?
回答1:
Based on some googling, it looks like you need to use the delegate method for the webView to allow external sites. Specifically, implement webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
with the following recommended implementation:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let requestURL = navigationAction.request.url?.absoluteString else { return }
if requestURL.contains("somepage.com") {
decisionHandler(.allow)
}
else {
// You don't need to cancel here, but you can implement your own logic here
decisionHandler(.cancel)
}
}
回答2:
Doing this on desktop browsers, where you have a local HTML file and a remote iFrame causes some security issues, so I expect you're hitting the same problem here.
Can you move your local content to a remote server? It doesn't have to be the same as your iframe content, although that will make your life easier.
If you have a lot of local data, then you could send a POST request for the parent page containing a JSON object of your local data.
来源:https://stackoverflow.com/questions/55596500/iframe-content-from-external-source-not-loading-in-local-html-file-on-ios