IOS UIWebView:如何添加监听器到DOM事件? [英] IOS UIWebView: How to add listeners to DOM events?

查看:202
本文介绍了IOS UIWebView:如何添加监听器到DOM事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在UIWebView中添加DOM事件侦听器?例如对于以下html:

How can I add listeners to DOM events in UIWebView? For example for the following html:

<button type="button" id="button1">Try it</button>

是否可以在加载UIWebView中的html的IOS应用程序中注册一个按钮点击事件的侦听器?

Is it possible to register a listener for a button click event in IOS application that loads html in UIWebView?

推荐答案

是的,您可以使用精美的url和UIWebViewDelegate方法来执行此操作。

Yes, you can do this with crafted url and UIWebViewDelegate methods.

首先,要在按钮标签上添加事件监听器,您应该执行如下所示的JavaScript(页面加载后)

First, to add event listener on button tag, you should execute javascript like below (after the page is loaded)

// 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的请求。

We bind a click event on the button, and when it's clicked, it will trigger a request to webView.

接下来我们要做的是拦截请求并在ObjC中执行所需的操作。

And the next thing we gotta do is to intercept the request and do what you want in 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...
    }
}

这篇关于IOS UIWebView:如何添加监听器到DOM事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆