在Mac应用程序中访问文件系统 JSContext

问题描述 投票:0回答:1

我正在做一个Mac应用,它使用JSContext来实现一些功能。

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

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

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

有没有什么方法可以让我在swift.Net中拥有这样的函数,并将一些自定义的函数指针传递到JSC.Net中。

    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个回答
2
投票

你可以设置一个消息处理程序来处理 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代码。

希望这对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.