简体   繁体   English

WKWebview从iPhone的文档目录加载外部脚本JS

[英]WKWebview load external script JS from iPhone's Document Directory

I am planning to use ChartIQ.js downloaded from remote server to iOS application's document directory, then load the downloaded ChartIQ.js adding it in tag in my local HTML file and use it in a WkWebview. 我打算使用从远程服务器下载的ChartIQ.js到iOS应用程序的文档目录,然后加载下载的ChartIQ.js,将其添加到我本地HTML文件的标记中,并在WkWebview中使用它。

Is this possible at all? 这有可能吗?

<script src="(Documents_Directory_Path)/chartiq.js"></script>

I think you can try to resolve your problem through script injection, so remove script src referring and load it (once downloaded and saved in the Document Directory) from Swift code with WKUserScript (I removed file exceptions checks but it's better you'll add it): 我想你可以尝试通过脚本注入解决你的问题,所以删除脚本src引用并加载它(一旦下载并保存在文档目录中)使用WKUserScript从Swift代码中删除 (我删除了文件异常检查但是你最好添加它):

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let webConfig = WKWebViewConfiguration()
let chartiq_js = try? String(contentsOfFile: documentsPath.appendingPathComponent("chartiq.js"), encoding: String.Encoding.utf8)
let script = WKUserScript(source: chartiq_js!, injectionTime: .atDocumentStart, forMainFrameOnly: false)
webConfig.userContentController.addUserScript(script)
wkWebV = WKWebView(frame: self.view.frame, configuration: webConfig)

You can check if the file has been correctly loaded using Safari Simulator debugger pointed to the iOS Simulator as soon as your WkWebview has been shown. 您可以在显示WkWebview后立即使用指向iOS模拟器的Safari模拟器调试器检查文件是否已正确加载。

UPDATE: 更新:

You can also load local resources using loadFileURL function (only from IOS9): 您还可以使用loadFileURL函数加载本地资源(仅限IOS9):

let fileURL = NSURL(fileURLWithPath: documentsPath.appendingPathComponent("index.html") as String) as URL
let filePath = NSURL(fileURLWithPath: documentsPath as String) as URL
wkWebV.loadFileURL(fileURL, allowingReadAccessTo: filePath)

note : in your html file you must refer to javascripts, images etc. only with a direct link: 注意 :在您的html文件中,您必须仅通过直接链接引用javascripts,图像等:

<script src="chartiq.js"></script>

And, of course, all your files must be downloaded all in the same directory. 当然,所有文件都必须全部下载到同一目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM