WKWebView不执行任何js代码

WKWebView不执行任何js代码

本文介绍了WKWebView不执行任何js代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WKWebView 在我的Xcode项目中呈现本地index.html文件.事实是,文件内的html和css代码已成功显示在webView内,但是 javaScript 却根本没有呈现.

I am rendering a local index.html file inside my Xcode project, using WKWebView. The thing is, the html and css code inside the file are successfully displayed inside the webView, but the javaScript however, is not rendered at all.

我在stackoverflow上搜索了与此问题类似的问题,我想到的是Apple不在本地html文件中执行js,为了执行js,我必须使用使用本地网络服务器GCDWebServer .

I have searched similar questions on this issue on stackoverflow and what I came up with is that Apple does not execute js in a local html file, and in order to execute js I am required to use a local webserver using GCDWebServer.

说实话,我是空洞的webServer概念的新手,我发现很难弄清楚如何在本地webServer中运行html,以及如何使用 GCDWebServer 来做到这一点.

To be honest I am new to the hole webServer concept and I'm finding it hard to figure how to run the html in a local webServer and how to this with GCDWebServer.

在WKWebView内的本地服务器上运行index.html文件的简单方法是什么

What's the simple way to run my index.html file on a local server inside WKWebView and how to do so

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let resourceUrl = Bundle.main.url(forResource: "index", withExtension: "html")
    let urlRequest = URLRequest.init(url: resourceUrl!)
    webView.load(urlRequest)

    webView.allowsBackForwardNavigationGestures = true

}

推荐答案

这是我设法创建一个 GCDWebServer 本地服务器的方法,其中js文件已使用 html 脚本成功渲染标记,并且不需要不需要JS注入,例如 WkUserscript evaluateJavaScript

This is how I managed to create a GCDWebServer local server with js files rendering successfully with html script tags and with no need for JS injections such as WkUserscript or evaluateJavaScript

我的代码:

import UIKit
import WebKit
import GCDWebServer

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate{


var wkWebView: WKWebView!
var webServer = GCDWebServer()

var contentController = WKUserContentController()


func initWebServer() {
    let folderPath = Bundle.main.path(forResource: "www", ofType: nil)

    webServer.addGETHandler(forBasePath: "/", directoryPath: folderPath!, indexFilename: "index.html", cacheAge: 0, allowRangeRequests: true)

    webServer.start(withPort: 8080, bonjourName: "GCD Web Server")

}

public override func viewDidLoad() {
    super.viewDidLoad()

    initWebServer()

    let config = WKWebViewConfiguration()
    config.userContentController = contentController


    wkWebView = WKWebView(frame: view.bounds, configuration: config)
    wkWebView.scrollView.bounces = false
    wkWebView.uiDelegate = self
    wkWebView.navigationDelegate = self
    view.addSubview(wkWebView!)

    wkWebView.load(URLRequest(url: webServer.serverURL!))
}

}

这篇关于WKWebView不执行任何js代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:41