UIWebView: get attributes from hyperlink clicked

I have an html page loaded through a UIWebView. If the user selects a link that looks like this:

<a webview="2" href="#!/accounts-cards/<%= item.acctno %>"></a> 

I can get the href value by clicking on the UIWebViewDelegate method from NSURLRequest:

 webView:shouldStartLoadWithRequest:navigationType: 

But how can I get the attribute value from this hyperlink (webview = " 2 "), assuming the attribute name is defined as "webview"?

+6
source share
2 answers

You can get your "webview" attribute using JavaScript, and after that you can send this attribute and its value to Objective-C native code.

Add this JavaScript code to the HTML page inside the script tag:

 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() { var attributeValue=links[i].webview; //this will give you your attribute(webview) value. reportBackToObjectiveC(attributeValue); }, true); } 

after that, your webViewDelegate method will call:

 - (BOOL)webView:(UIWebView *)wView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ { if (navigationType == UIWebViewNavigationTypeLinkClicked) { NSURL *URL = [request URL]; if ([[URL scheme] isEqualToString:@"callback"]) { //You can get here your attribute value. } } 
0
source

You need to change the href of your links. First enter a javascript script that fixes your links.

 - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *js = @"var allElements = document.getElementsByTagName('a');" "for (var i = 0; i < allElements.length; i++) {" " attribute = allElements[i].getAttribute('webview');" " if (attribute) {" " allElements[i].href = allElements[i].href + '&' + attribute;" " }" "}"; [webView stringByEvaluatingJavaScriptFromString:js]; } 

Links will be converted to format (note & 2 in the href attribute): <a webview="2" href="#!/accounts-cards/<%= item.acctno %>&2"></a> Then you can get your callback and parse the value of the webview parameter:

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"&"]; if (array.count > 2) { NSLog(@"webview value = %@", array[1]); } return YES; } 
0
source

All Articles