使用Swift在iOS WKWebview中捕获Javascript事件 [英] Catch Javascript Event in iOS WKWebview with Swift
问题描述
我正在使用网络编程语言构建应用程序,并希望在用户单击HTML按钮时启动相机。由于我希望我的相机视图是自定义的,我需要使用Swift进行设计。所以当用户点击这个HTML按钮时,我想在Swift中捕获这个点击,这样我就可以开始我的原生相机视图了。
I am building an app with web programming languages and want to start the camera when the user clicks on an HTML button. Since I want my camera view to be a custom one, I need to design it with Swift. So when the user clicks on this HTML button, I want to "catch" this click in Swift so I can start my native camera view.
我知道它可以完成使用WKWebview,但我真的不知道该怎么做。
I know it can be done with the WKWebview, but I don't really know how to do that.
例如,我的Javascript(jQuery)代码可能看起来像这样:
For example, my Javascript (jQuery) code could look like that :
// User clicks to start the native camera with Swift
$(".camera_button").click(function() {
// Function to call the camera view from JS to Swift
});
你能帮我这么做吗?
谢谢。
推荐答案
基于@Alex Pelletier的回答,这真的帮助了我,这里是我的问题的解决方案。
Based on the answer from @Alex Pelletier, which really helped me, here is the solution the my question.
在我的loadView()函数中,这就是我所拥有的:
In my "loadView()" function, here is what I have :
let contentController = WKUserContentController();
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: CGRectZero, configuration: config)
webView.navigationDelegate = self
view = webView
我处理发送到Swift的Javascript事件的函数:
My function to handle the Javascript event which is sent to Swift :
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
{
if(message.name == "callbackHandler") {
print("Launch my Native Camera")
}
}
...最后,我的Javascript(jQuery)代码当我的相机按钮(用HTML)发生点击时:
... And finally, my Javascript (jQuery) code when a click happens on my camera button (in HTML) :
$(document).ready(function() {
function callNativeApp () {
try {
webkit.messageHandlers.callbackHandler.postMessage("camera");
} catch(err) {
console.log('The native context does not exist yet');
}
}
$(".menu-camera-icon").click(function() {
callNativeApp();
});
});
我希望它能帮到别人:-)!
I hope it will help someone else :-) !
这篇关于使用Swift在iOS WKWebview中捕获Javascript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!