Lev Dubinets
Lev Dubinets

Reputation: 808

Access to filesystem in a Mac App JSContext

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?

Upvotes: 1

Views: 200

Answers (1)

Tritonal
Tritonal

Reputation: 831

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.

Upvotes: 2

Related Questions