This post和this post解决了使用JavaScript在移动版Safari中打开WKWebView链接的问题,但由于某些原因,所提供的解决方案无效。
下面的代码包含了不同解决方案的元素,但单击按钮后链接仍无法打开。
事实上,webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy)
和userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
甚至都没有被调用。
HTML:
<html>
<style type="text/css">
#button { width: 100px; height: 50px; background: red; }
</style>
<div id="button">CLICK TO GO</div>
<script type="text/javascript">
var button = document.getElementById("button");
button.addEventListener("click", doTest);
function doTest() {
window.open("http://www.google.com", target="_blank");
button.innerHTML = "HEY";
}
</script>
</html>
的ViewController:
class ViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView?
let webViewContentController = WKUserContentController()
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
config.userContentController = webViewContentController
webView = WKWebView(frame: view.bounds, configuration: config)
webView!.navigationDelegate = self
webView!.uiDelegate = self //must have this
var fileURL = URL(fileURLWithPath: Bundle.main.path(forResource:"Mooncake.html", ofType: nil)!)
webView!.loadFileURL(fileURL, allowingReadAccessTo: fileURL)
view.addSubview(webView!)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
// this handles target=_blank links by opening them in the same view
func webView(webView: WKWebView!, createWebViewWithConfiguration configuration: WKWebViewConfiguration!, forNavigationAction navigationAction: WKNavigationAction!, windowFeatures: WKWindowFeatures!) -> WKWebView! {
if navigationAction.targetFrame == nil {
let url = navigationAction.request.url!
let urlString = url.description.lowercased()
if urlString.contains("http://") || urlString.contains("https://") || urlString.contains("mailto:") {
UIApplication.shared.openURL(url)
}
}
return nil
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if navigationAction.targetFrame == nil {
webView.load(navigationAction.request)
}
}
}
答案 0 :(得分:0)
问题是使用过时的函数定义,从SO答案中解除,
webView(webView: WKWebView!, createWebViewWithConfiguration configuration: WKWebViewConfiguration!, forNavigationAction navigationAction: WKNavigationAction!, windowFeatures: WKWindowFeatures!) -> WKWebView!
和
webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void)
使用类docs定义的Swift 3函数定义解决了这个问题。