0

I want to make a static web view app in Swift. HTML and CSS are loading but not local javascript files. (they are jquery, bootstrap, popper and my scripts)

I tried this:

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "assets")!
        loadJS()
        webView.loadFileURL(url, allowingReadAccessTo: url)
    }

    func loadJS() {
        let jquery = Bundle.main.url(forResource: "jquery", withExtension: "js", subdirectory: "assets/js")!
        let bootstrap = Bundle.main.url(forResource: "bootstrap", withExtension: "js", subdirectory: "assets/js")!
        let popper = Bundle.main.url(forResource: "popper", withExtension: "js", subdirectory: "assets/js")!
        let modules = Bundle.main.url(forResource: "modules", withExtension: "js", subdirectory: "assets/js")!
        do {
            let content1 = try String(contentsOfFile: jquery.path, encoding: String.Encoding.utf8)
            let content2 = try String(contentsOfFile: bootstrap.path, encoding: String.Encoding.utf8)
            let content3 = try String(contentsOfFile: popper.path, encoding: String.Encoding.utf8)
            let content4 = try String(contentsOfFile: modules.path, encoding: String.Encoding.utf8)
            let controller = WKUserContentController()
            controller.addUserScript(WKUserScript(source: content1, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
            controller.addUserScript(WKUserScript(source: content2, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
            controller.addUserScript(WKUserScript(source: content3, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
            controller.addUserScript(WKUserScript(source: content4, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true))
            print(controller.userScripts)
        } catch {
            print(error)
        }
    }
  • Does this answer your question? [javascript embedded in html not running in wkwebview](https://stackoverflow.com/questions/56583506/javascript-embedded-in-html-not-running-in-wkwebview) – koen May 27 '20 at 23:10
  • @koen no It doesn't. I don't need to call functions from Swift. I need html to call himself jQuery and other functions – G. Trematerra May 28 '20 at 00:09
  • https://stackoverflow.com/questions/34597159/loading-local-css-js-files-into-wkwebview. hope it helps ! – Vinayaka S Yattinahalli May 28 '20 at 04:17

0 Answers0