如何在UIWebView中添加侦听器到DOM事件?例如,对于以下html:
<button type="button" id="button1">Try it</button>
是否可以在IOS应用程序中为在UIWebView中加载html的按钮单击事件注册一个侦听器?
答案 0 :(得分:8)
是的,您可以使用精心设计的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...
}
}
答案 1 :(得分:0)
这是在UIWebView
中点击链接时截取的Swift方式:
让自己成为代表:
class ViewController: UIViewController, UIWebViewDelegate { //... }
并指定它:
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
//...
}
现在我们可以用它来拦截:
func webViewDidFinishLoad(_ webView: UIWebView) {
if (currentURL?.lowercased().range(of:"some/url") != nil) {
webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('a')[0].onclick = function() {window.location = 'injected://loadPDF1'; return false;}")
}
}
// Sent before a web view begins loading a frame.
func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
// intercept all injected page calls
if (shouldStartLoadWith.url?.scheme == "injected") {
return false;
}
return true;
}