Reputation: 13
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?
Upvotes: 1
Views: 2078
Reputation: 7708
Try injecting it as user script. If your folder structure is like this, use the below function to load it as user script
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())
}
Upvotes: 1