UIWebView and click link

百般思念 提交于 2019-12-10 06:50:13

问题


I know that most likely the answer is very obvious, but I've looked everywhere on the internet and I have not found anything. I use this method to see if the user presses on the WebView

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {

I can assure you that it works.

What I want to do is to make different actions according to the id

es

<a id="hello" href="..."><img src="..." /></a>

once the delegate detect "touch click" on the img with the "hello" id, I would do some custom stuff, like [self callSomething];

Could you show me how to do it using a sample code? thanks


回答1:


change your code as follows

  <a id="hello" href='didTap://image><img src="..." /></a>

and in the delegate method try like this.

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
 {     
NSString *absoluteUrl = [[request URL] absoluteString];
 NSString*temp=[absoluteUrl stringByReplacingOccurrencesOfString:@"@" withString:@""];

if ([temp isEqualToString:@"didTap://image"])
{
    [self your method];
}
return YES;
    }



回答2:


UIWebView can't receive id from dom element but one thing you can do is pass value in href url with a parameter hello like:

<a id="hello" href="//myurl?id=hello"><img src="..." /></a>

and you can get parameter as:

URLParser *parameter = [[URLParser alloc] initWithURLString:@"http://myurl/id=hello"];
NSString *id = [parameter valueForVariable:@"id"];



回答3:


To achieve this you should put javascript onClick handler to any DOM element you need

f.e

<a onClick="callNativeSelector('doSomething');" ... > </a>

javascript function callNativeSelector(nativeSelector) { // put native selector as param
    window.location = "customAction://"+nativeSelector;
}

On UIWebView delegate's method ignore links like above

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

  if ([[request.URL scheme] isEqualToString:@"customAction"]) {
        //Fetching image URL
        NSLog(@"Custom selector is %@", [request.URL host])
        ...
        // Always return NO not to allow `UIWebView` process such links
        return NO; 
    }
    ....
}

There are benefits from my point of view:

  • Not associated with specific DOM element like <a href=...>, you can assign such handler to anything you need

  • Not associated with html id attribute

  • Ability inside UIWebView ignore loading such links and just execute your customSelector nativly



来源:https://stackoverflow.com/questions/18464283/uiwebview-and-click-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!