如何在UIWebView中添加侦听器到DOM事件?例如,对于以下html:
是否可以在IOS应用程序中为按钮单击事件注册一个侦听器,该应用程序在UIWebView中加载html?
是的,您可以使用精心设计的url和UIWebViewDelegate方法执行此操作.
首先,要在按钮标记上添加事件监听器,您应该像下面一样执行javascript(在加载页面之后)
// In the UIWebViewDelegate - (void)webViewDidFinishLoad:(UIWebView *)webView { if (/* when the loaded url is the target */) { NSString *js = @"document.getElementById('button').click = function() { window.location = 'my-protocol://dummmy.com/maybe/some/data';}"; [webView stringByEvaluatingJavaScriptFromString: js]; } }
我们在按钮上绑定一个click事件,当它被单击时,它将触发对webView的请求.
接下来我们要做的是拦截请求并在ObjC中做你想做的事.
// In the UIWebViewDelegate - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (/* when the url of the request is the crafted url */) { // call your objc method... } }