iosswiftwkwebviewgcdwebserver

WKWebView not executing any js code


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.

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.

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.

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

here is my code:

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

}

Solution

  • 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

    my code:

    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!))
    }
    
    }