是否可以通过使用 WKWebView loadHTMLString 方法加载的 html 从 Xcode 项目加载脚本文件?
例如,如果我有一个名为 DemoProject 的项目,根目录中有名为 script1.js 和 script2.js 的 javascript 文件。然后我正在加载一个试图引用这些文件的 html 字符串。那可能吗?如果是这样,我该如何正确引用这些文件?
最佳答案
尝试将其作为用户脚本注入(inject)。 如果您的文件夹结构是这样的,请使用以下函数将其加载为用户脚本
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
}
将其添加到 Controller
func registerScriptsAndEvents() {
let controller = self.wkWebView.configuration.userContentController
// Load the entire script to the document
controller.addUserScript(fetchScript())
}
关于ios - 从 HTML 字符串 wkwebview 加载脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43369683/