【问题标题】:Access to filesystem in a Mac App JSContext在 Mac App JSContext 中访问文件系统
【发布时间】:2023-03-17 08:38:01
【问题描述】:

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

它使用这样的调用(其中ctx 是JSContext):

let result: JSValue? = ctx.evaluateScript("someFunction")?.call(withArguments: [someArg1!, someArg2])

在someFunction 脚本中,我们需要解析一个目录并确定它是否存在于文件系统中。据我所知,Apple 的 JavaScriptCore API 没有文件系统访问权限。

有什么方法可以让我在 swift 中拥有这样的功能:

    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 以调用该函数?

【问题讨论】:

    标签: swift macos cocoa javascriptcore jscontext


    【解决方案1】:

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多