如何在 UIWebView 中添加 DOM 事件监听器?例如对于以下 html:
<button type="button" id="button1">Try it</button>
是否可以在 UIWebView 中加载 html 的 IOS 应用程序中注册按钮单击事件的侦听器?
是的,您可以使用精心设计的 url 和 WebView 委托方法来做到这一点。
首先,要在按钮标签上添加事件侦听器,您应该像下面一样执行 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];
}
}
我们在按钮上绑定一个点击事件,当点击时,就会触发对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...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)