[英]Access to filesystem in a Mac App JSContext
我正在開發一個使用 JSContext 來實現某些功能的 Mac 應用程序。
它使用這樣的調用(其中ctx
是JSContext
):
let result: JSValue? = ctx.evaluateScript("someFunction")?.call(withArguments: [someArg1!, someArg2])
在someFunction
腳本中,我們需要解析一個目錄並確定它是否存在於文件系統中。 據我所知,Apple 的 JavaScriptCore API 沒有文件系統訪問權限。
有什么方法可以讓我在 swift 中有這樣的 function:
public static func isAppDirectory(_ path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
並將一些自定義 function 指針傳遞到 JSContext 以調用該 function?
您可以為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 代碼。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.