草庐IT

IOS UIWebView : How to add listeners to DOM events?

coder 2023-09-25 原文

如何在 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/

有关IOS UIWebView : How to add listeners to DOM events?的更多相关文章

随机推荐