如何在UIWebView中可靠地检测链接点击? [英] How can I reliably detect a link click in UIWebView?
问题描述
我有一个 UIWebView
,我需要在用户点击链接时执行某些操作。有一个委托回调,可以用来检测水龙头:
I have a UIWebView
and I need to do something when user taps a link. There’s a delegate callback that can be used to detect the taps:
- (BOOL) webView: (UIWebView*) webView
shouldStartLoadWithRequest: (NSURLRequest*) request
navigationType: (UIWebViewNavigationType) navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
…
}
}
问题是此代码无法处理所有链接点击。例如,一个普通的Google搜索结果页面对链接做了一些奇怪的事情:
The problem is that this code doesn’t handle all link clicks. As an example, a plain Google Search results page does something weird with the links:
<a href="http://example.com/" class="l" onmousedown="return rwt(…)">
<em>Link Text</em>
</a>
rwt
函数导致链接没有在点击时触发 UIWebViewNavigationTypeLinkClicked
事件。有没有办法可靠地检测落入导航到其他页面桶的所有事件?
The rwt
function results in the links not triggering the UIWebViewNavigationTypeLinkClicked
event when tapped. Is there a way to reliably detect all events that fall into the "navigate to some other page" bucket?
推荐答案
到目前为止我已达到以下解决方案。首先,我在加载时向页面注入一些JS代码:
So far I have arrived at the following solution. First, I inject some JS code into the page when loaded:
function reportBackToObjectiveC(string)
{
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "callback://" + string);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
links[i].addEventListener("click", function() {
reportBackToObjectiveC("link-clicked");
}, true);
}
当用户点击链接时,由于 webView:shouldStartLoadWithRequest:navigationType:
委托电话:
When user taps a link, I know it in advance thanks to the webView:shouldStartLoadWithRequest: navigationType:
delegate call:
if ([[[request URL] scheme] isEqualToString:@"callback"]) {
[self setNavigationLeavingCurrentPage:YES];
return NO;
}
然后如果另一个请求到来并且 _navigationLeavingCurrentPage
是真的,我知道用户点击了一个链接,即使导航类型标志是 UIWebViewNavigationTypeOther
。我仍然需要广泛地测试解决方案,因为我担心它会导致一些误报。
Then if another request comes and _navigationLeavingCurrentPage
is true, I know the user has clicked a link even though the navigation type flag is UIWebViewNavigationTypeOther
. I still have to test the solution extensively, for I’m afraid that it will lead to some false positives.
这篇关于如何在UIWebView中可靠地检测链接点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!