UIWebView and click the link

I know that, most likely, the answer is very obvious, but I looked everywhere on the Internet and I did not find anything. I use this method to find out if a user clicks on a 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 do different actions according to id

s

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

as soon as the delegate detects a "touch click" on img with the identifier "hello", I would do some custom things, for example [self callSomething];

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

+4
source share
3 answers

change your code as follows

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

and in the delegate method try to do 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; } 
+4
source

UIWebView cannot accept an identifier from a dom element, but one thing you can do is pass a value to the href url with the hello parameter, for example:

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

and you can get the parameter as:

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

To achieve this, you must place the onClick javascript handler in any DOM element that you need.

fe

 <a onClick="callNativeSelector('doSomething');" ... > </a> javascript function callNativeSelector(nativeSelector) { // put native selector as param window.location = "customAction://"+nativeSelector; } 

In UIWebView delegate case, 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; } .... } 

I have my advantages:

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

  • Not associated with html id attribute

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

+2
source

Source: https://habr.com/ru/post/1499120/


All Articles