【问题标题】:Call a native Swift function from JavaScript in a WebView在 WebView 中从 JavaScript 调用本机 Swift 函数
【发布时间】:2016-10-07 11:57:46
【问题描述】:

我正在尝试重现该项目的结果:https://github.com/victorchee/JavaScriptCoreDemo

也就是说,我想重现第二个按钮,它从 Swift 调用本机函数。

我遇到的问题是以下代码:

jsContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as? JSContext

我得到了休闲错误:

2016-10-07 18:39:01.664 JSCore-Test-01[17603:689101] *** WebKit discarded an uncaught exception in the webView:didFinishLoadForFrame: delegate: <NSUnknownKeyException> [<WebView 0x6080001208c0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key documentView.

此 iOS 代码在 Mac OS X 中的等效项是什么?

【问题讨论】:

    标签: swift macos webview javascriptcore


    【解决方案1】:

    Small research 表明这一切都是 macOS 的 WebView API 中的public API。要获取上下文,只需访问

    webView.mainFrame.globalContext
    

    对于基于 C 的 API JSGlobalContextRef 对象,或

    webView.mainFrame.javaScriptContext
    

    对于基于 Objective-C 的JSContext*

    【讨论】:

    • 我花了几个小时研究这个问题并试图解决它!使用webView.mainFrame.javaScriptContext 确实消除了错误,但它不会像documentView.webView.mainFrame.javaScriptContext 为iOS 应用程序所做的那样加载JSContext*。这是我仍然使用documentView 作为例外github.com/moon47usaco/JSCore-Test-03/tree/master 的Mac OS X 的说明@
    • 不要访问主框架上下文,而是尝试使用此委托方法:developer.apple.com/reference/webkit/webframeloaddelegate/…
    • 这允许jsContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as? JSContext 无一例外但仍然没有按钮交互。在没有分配到jsContext 的情况下尝试使用context.objectForKeyedSubscript("show")?.callWithArguments(["Swift call"]),但按钮仍然没有执行任何操作。为什么这在 OS X 中要困难得多?不过感谢您的建议。
    • @Moon47 你尝试过委托方法吗?也许它返回的上下文与主框架上下文不同。
    • 我从 GitHub 上的原始项目创建者那里得到了答案。我是用let jsContext = frame.javaScriptContextlet jsContext = JSContext(jsGlobalContextRef: frame.globalContext)
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2011-05-18
    • 2019-05-31
    • 2018-03-07
    相关资源
    最近更新 更多