swift - 在 Mac App JSContext 中访问文件系统
问题描述
我正在开发一个使用 JSContext 来实现某些功能的 Mac 应用程序。
它使用这样的调用(ctx
a在哪里JSContext
):
let result: JSValue? = ctx.evaluateScript("someFunction")?.call(withArguments: [someArg1!, someArg2])
在someFunction
脚本内部,我们需要解析一个目录并确定它是否存在于文件系统中。据我所知,Apple 的 JavaScriptCore API 没有文件系统访问权限。
有什么方法可以让我快速拥有这样的功能:
public static func isAppDirectory(_ path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
并将一些自定义函数指针传递给 JSContext 以调用该函数?
解决方案
您可以为WKWebView
. 然后,您可以在 Web 视图和您的应用程序之间传递数据。用 Objective-C 回答,但很容易适应。(我认为您也应该能够在 JavaScriptCore 中设置消息处理程序,但我不熟悉它。)
// Set this while configuring WKWebView.
// For this example, we'll use self as the message handler,
// meaning the class that originally sets up the view
[webView.configuration.userContentController addScriptMessageHandler:self name:@"testPath"];
您现在可以从 JavaScript 向应用程序发送一个字符串:
function testPath(path) {
window.webkit.messageHandlers.testPath.postMessage(path);
}
Objective-C 中的消息处理程序:
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *) message{
// .name is the handler's name,
// .body is the message itself, in this case the path
if ([message.name isEqualToString:@"testPath"]) {
...
[webView evaluateJavaScript:@"doSomething()"];
}
}
请注意,webkit 消息是异步的,因此您需要实现某种结构以便稍后继续运行您的 JS 代码。
希望这可以帮助。
推荐阅读
- laravel - 致命错误:已用完允许的 134217728 字节内存大小(尝试分配 53091665 字节)-Linode 服务器图像上传
- http - 如何在 POST 中的 JSON 中发送 JSON
- java - AIX - 无法创建 VM 线程。系统资源不足
- scala - 如何在 Play 框架的 Scala 模板中的 if 块中添加多个“OR”和“AND”条件
- llvm - 从分支指令中提取 MachineBasicBlock
- sql - Oracle Db:查询 Ctx_Ddl 首选项
- javascript - 如何将右键单击对话框上的画布保存为 jpg
- r - 列 dplyr 的 row_number 等价物
- javascript - 使用google api测量3个标记之间的距离
- github - github上每个作业的无人机更新状态