1

Is it possible to load script files from Xcode project via html loaded with WKWebView loadHTMLString method?

For example if I have a project named DemoProject, with javascript files called script1.js and script2.js in the root directory. Then I'm loading an html string that tries to reference those files. Is that possible? If so how do I properly reference those files?

7
  • Try this <script src="script1.js"></script> <script src="script2.js"></script> Commented Apr 12, 2017 at 12:50
  • I did, it's not being found. Commented Apr 12, 2017 at 12:51
  • Are HTML file and Scripts both in the same Target? Commented Apr 12, 2017 at 12:52
  • There's no html file, I load a string, which contains html, into the wkwebview. That string contains <script src="script1.js"></script> <script src="script2.js"></script>. Those files are located in the project's root directory. Commented Apr 12, 2017 at 12:55
  • What about convert files content to string and then inject with webView.stringByEvaluatingJavascript? i dont remember the exact name of the function but you can check it out. Hope it helps Commented Apr 12, 2017 at 15:17

1 Answer 1

1

Try injecting it as user script. If your folder structure is like this, use the below function to load it as user script

enter image description here

private func fetchScript() -> WKUserScript!{

    var jsScript = ""
    if let jsPath = Bundle.main.path(forResource: "hello", ofType: "js", inDirectory: "scripts"){
        do
        {
            jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
        }catch{

            print("Error")
        }
    }

    let wkAlertScript = WKUserScript(source: jsScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    return wkAlertScript
}

Add it to controller

func registerScriptsAndEvents() {

    let controller = self.wkWebView.configuration.userContentController
    // Load the entire script to the document
    controller.addUserScript(fetchScript())
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can check this project github.com/anoop4real/WKWebViewExperiments i tried a lot of things
@anoop4real, the hello.js file should be called through start.html file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.