Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView ignores inline anchor/link

I'm using a UIWebViewthat loads HTML from a database string using webView.loadHTMLString(self.htmlContent, baseURL: nil)

The htmlContent contains the following:

<ul class="anchorNavigation">
  <li>
    <a href="#parsys_47728" class="">1. Inline Test Link</a>
  </li>
  <li>
    <a href="#parsys_00061" class="">2. Inline Test Link</a>
  </li>
  ...
</ul>

... and later in the HTML:

...
<a href="#" name="parsys_00061"></a>
...

However, whenever I click the inline link in the webView nothing happens.

What I've tried so far:

  • Changing the anchor tag to 'real' valid W3C HTML. E.g. <a id='parsys_47728'>Test</a>
  • Saving the HTML to a file in the temp directory and loading it using loadRequest(). E.g. let path = tempDirectory.URLByAppendingPathComponent("content.html") and webView.loadRequest(NSURLRequest(URL: path))
  • Intercepting the loadRequest method by implementing the func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool delegate. The request.URL says something strange like: "applewebdata://1D9D74C2-BBB4-422F-97A7-554BCCD0055A#parsys_47728"

I don't have any idea anymore how to achieve this. I know from previous projects that local HTML files in the bundle work with inline links. I just cannot figure out why this doesn't work.

Help much appreciated! Thank you!

like image 633
Chris Avatar asked Sep 24 '26 17:09

Chris


1 Answers

If there's a fragment (e.g., #anchorName), then use JavaScript to scroll. Otherwise, assume it's a link without a fragment and use openURL.

// UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
        // NSLog(@"request.URL  %@",request.URL); // e.g., file:///.../myApp.app/#anchorName
        NSString *anchorName = request.URL.fragment; // e,g, "anchorName"    
        if ( anchorName ) {
            [webView stringByEvaluatingJavaScriptFromString:[NSString swf:@"window.location.hash='%@';",anchorName]];
            return NO;

        } else { // assume http://
            [[UIApplication sharedApplication] openURL:[request URL]];
            return NO;
        }
    }
    return YES;
}

I'm still looking for a way to have the scroll position change smoothly (animated) rather than jumping.

like image 96
Jeff Avatar answered Sep 29 '26 00:09

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!