Access to filesystem in a Mac App JSContext

倾然丶 夕夏残阳落幕 提交于 2020-06-17 00:56:33

问题


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

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

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

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
    }

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


回答1:


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"];

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

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

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()"];
    }
}

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

Hope this helps.



来源:https://stackoverflow.com/questions/61315468/access-to-filesystem-in-a-mac-app-jscontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!