IOS UIWebView : How to add listeners to DOM events?

标签 ios events dom uiwebview

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

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

是否可以在 UIWebView 中加载 html 的 IOS 应用程序中为按钮单击事件注册监听器?

最佳答案

是的,您可以使用精心设计的 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];
    }
}

我们在按钮上绑定(bind)一个点击事件,点击后会触发对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...
    }
}

关于IOS UIWebView : How to add listeners to DOM events?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20328519/

相关文章:

events - 在 CellTable 单元格中添加双击事件 - GWT

C#:在不相关的类之间共享属性、事件和方法

iOS 应用程序的存档数据无法正确加载

ios - cocos2d中的图像背景问题

c# - 表达 C# 条件, "if a mouse/keyboard action has not occurred in the last ' n'秒”

javascript - 以 block 的形式将项目添加到 DOM

asp.net - 如何在回传中保持 DragPanelExtender 的位置?

iphone - 尝试将字符串转换为日期

ios - 已解析的 JSON 数据未打印到控制台

javascript - 什么是 offsetHeight、clientHeight、scrollHeight?