【问题标题】:WKWebview load external script JS from iPhone's Document DirectoryWKWebview 从 iPhone 的文档目录加载外部脚本 JS
【发布时间】:2023-03-30 09:28:01
【问题描述】:

我打算使用从远程服务器下载的 ChartIQ.js 到 iOS 应用程序的文档目录,然后加载下载的 ChartIQ.js 并将其添加到我本地 HTML 文件的标记中,并在 WkWebview 中使用它。

这可能吗?

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

【问题讨论】:

    标签: javascript ios iphone swift wkwebview


    【解决方案1】:

    我认为你可以尝试通过脚本注入来解决你的问题,所以删除脚本 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)
    

    您可以在 WkWebview 显示后立即使用指向 iOS 模拟器的 Safari 模拟器调试器检查文件是否已正确加载。

    更新:

    你也可以使用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)
    

    注意:在您的 html 文件中,您必须仅通过直接链接引用 javascript、图像等:

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

    当然,所有文件都必须下载到同一个目录中。

    【讨论】:

    • 一个非常好的和详细的解释.. +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2020-10-22
    • 1970-01-01
    相关资源
    最近更新 更多