在Mac App JSContext中访问文件系统 [英] Access to filesystem in a Mac App JSContext

查看:156
本文介绍了在Mac App JSContext中访问文件系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究使用JSContext进行某些功能的Mac应用.

I am working on a Mac app that uses a JSContext for some functionality.

它使用这样的调用(其中ctxJSContext):

It uses a call like this (where ctx is a JSContext):

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

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

Inside the someFunction script, we need to parse a directory and determine whether it exists on the filesystem. Apple's JavaScriptCore API does not have filesystem access as far as I can tell.

有什么办法可以让我迅速拥有这样的功能:

Is there some way I can have a function like this in 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中以调用该函数?

and pass some custom function pointer into the JSContext to call that function?

推荐答案

您可以为WKWebView设置消息处理程序.然后,您可以在Web视图和您的应用之间传递数据.在Objective-C中回答,但很容易适应. (我认为您也应该能够在JavaScriptCore中设置消息处理程序,但我对此并不熟悉.)

You could set up a message handler for a WKWebView. You can then pass data between web view and your app. Answer in Objective-C, but easily adaptable. (I think you should be able to set the message handlers in JavaScriptCore too, but I'm not familiar with it.)

// 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向应用程序发送字符串:

You can now send a string to the app from JavaScript:

function testPath(path) {
    window.webkit.messageHandlers.testPath.postMessage(path);
}

Objective-C中的消息处理程序:

The message handler in 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代码.

Note that the webkit messages are asynchronous, so you need to implement some sort of structure to continue running your JS code later.

希望这会有所帮助.

这篇关于在Mac App JSContext中访问文件系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆