gpt4 book ai didi

嵌入在 html 中的 javascript 未在 wkwebview 中运行

转载 作者:行者123 更新时间:2023-11-28 07:26:03 26 4
gpt4 key购买 nike

我正在使用 UIWebView 的应用程序中实现 wkwebview。当指向其中嵌入了 javascript 的本地 html 文件时,我无法执行 javascript。 javascript 被剥离以做一个简单的警报并加载一个基本的谷歌地图。这些都没有被执行。我需要运行本地服务器吗? GCD网络服务器..

我应该补充一点,html/javascript 在 safari、google 浏览器中都没有问题。

尝试的解决方案包括:1. AppTransportSecuritySettings 允许任意加载。2. ViewController.swift webview.configuration.preferences.javaScriptEnabled = true3. 这个问题解决了这个问题,并说在 iOS 10.3 中已修复 Load Javascript files through HTML file on WKWebView in iOS模拟器正在运行 12.14.这个问题也解决了要求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 都不起作用,我应该得到一个警报,并且应该显示一个简单的谷歌地图。我需要查看本地网络服务器 GCDWebserver 吗?

最佳答案

您应该在此 WKNavigationDelegate 方法中调用您的 javascript,该方法在 webview 完成加载时调用。

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("initMap()", completionHandler: { (value, err) in
// Handle response here.
})
}

此外,我不确定您为什么要调用两个不同的 webview.load() 请求 - 也许不要那样做?

关于嵌入在 html 中的 javascript 未在 wkwebview 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com