views:

420

answers:

2

I'm displaying some HTML with links in a UIWebView. I want the links to open in Safari after the user confirmed that the link should really be opened.

Opening the link works fine, but if the user cancels, the link remains selected and is highlighted in blue. How can I deselect the link and get rid of the highlighting?

- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
 if (navigationType == UIWebViewNavigationTypeLinkClicked) {
  self.url = request.URL;
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Open the Link in Safari" message:[request.URL absoluteString] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK"];
  [alert show];
  [alert release];
        return false;
    }
    return true;
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
 if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:url];
 }
 // Insert magic deselection code here
}

Update: It seems [UIWebView stringByEvaluatingJavaScriptFromString:] is the way to go. But how exactly? I tried

for (var e in document.getElementsByTag("a")) {e.blur();}

but to no avail.

+1  A: 

You'll have to use UIWebView stringByEvaluatingJavaScriptFromString: with something like document.getElementById('yourlinksid') to set the state to deselected.

If the file isn't too big you might try using js to select all elements (with an xpath or css selector get function) and then set them as deselected, rather than try to find the specific one. I don't have a JS recipe for this off the top of my head but the UIWebView JS interface is how you'll have to do this.

Nimrod
+2  A: 

I think this is a symptom of the underlying WebKit code and the way that MobileSafari emulates "mouse" position.

You could try setting the CSS for those elements to something like:

a.YourElementClassName:hover { text-decoration: none; }

If my guess is right, the reason that it's turning blue and getting underlined is because Safari thinks the mouse cursor is now over that element. Using the right combination of CSS selectors should fix it. (Might need to add :visited and :visited:hover just to be sure.)

clee
You are right, this solved the problem. Unfortunately, it seems I can't accept the answer :(
Daniel Hepper