我正在使用UIWebView的应用程序中实现wkwebview。指向其中嵌入了javascript的本地html文件时,我无法执行javascript。剥离了javascript,以发出简单的警报并加载基本的Google地图。这些都没有执行。我需要运行本地服务器吗? GCDWebserver ..
我应该补充一点,html / javascript在safari中工作,谷歌浏览器没问题。
尝试的解决方案包括: 1. AppTransportSecuritySettings AllowArbitrary加载。 2. ViewController.swift webview.configuration.preferences.javaScriptEnabled = true 3.该问题解决了该问题,并说它已在iOS 10.3 Load Javascript files through HTML file on WKWebView in iOS中修复,模拟器正在运行12.1 4.该问题还回答了要求GCDWebserver能够使用wkwebview执行javascript的问题。 WKWebView not executing any js code但是,这在iOS的最新版本中也得到解决。这是一些代码:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
//@IBOutlet var googleMap: WKWebView!
var webview: WKWebView!
override func loadView() {
webview = WKWebView()
webview.navigationDelegate = self
view = webview
}
override func viewDidLoad() {
super.viewDidLoad()
//let url = URL(string: "https://schallerf1.com")!
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "www")!
webview.load(URLRequest(url: url))
webview.allowsBackForwardNavigationGestures = true
let request = URLRequest(url: url)
webview.configuration.preferences.javaScriptEnabled = true
webview.load(request)
}
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<b>WHYYYYYYYYYY!!!!</b>
<div style="height:100%;width:100%;" id="map"></div>
<script type="text/javascript">
var name = "TESTTESTTEST";
alert('code: ' + name + '\n');
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 39.976068, lng: -83.003297},
zoom: 8
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxx&callback=initMap"></script>
</body>
</html>
所有JavaScript均不起作用,我应该收到警报,并显示一个简单的Google地图。我需要查看本地Web服务器GCDWebserver吗?
答案 0 :(得分:0)
您应该使用此WKNavigationDelegate
方法来调用javascript,当Webview完成加载时会调用该方法。
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("initMap()", completionHandler: { (value, err) in
// Handle response here.
})
}
此外,我不确定为什么您要调用两个不同的webview.load()
请求-也许不这样做?