首页 > 解决方案 > 在 Mac App JSContext 中访问文件系统

问题描述

我正在开发一个使用 JSContext 来实现某些功能的 Mac 应用程序。

它使用这样的调用(ctxa在哪里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 以调用该函数?

标签: swiftmacoscocoajavascriptcorejscontext

解决方案


您可以为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 代码。

希望这可以帮助。


推荐阅读