UIWebView and click link

2019-05-07 18:53发布

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

标签: ios uiwebview
3条回答
在下西门庆
2楼-- · 2019-05-07 19:07

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;
    }
查看更多
Ridiculous、
3楼-- · 2019-05-07 19:11

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

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-05-07 19:25

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"];
查看更多
登录 后发表回答