Search code examples
iosiphoneipaduiwebviewios11

Unable to move UIWebView to a specified section in iOS11 (iPad)


We have used the below lines of code to move to the web view:

[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash=\'#-1\';"]];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.location.hash=\'#%@\';", index]];

but somehow this code doesn't work only in iPad. Here is how I initialised the web view:

webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[webView setDelegate:self];
[webView.scrollView setDelegate:self];
[webView setBackgroundColor:WHITECOLOR];
[webView setScalesPageToFit:YES];
[webView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview: webView];

Could someone please guide me how to debug it.


Solution

  • In iOS11 location.hash seems to be broken, but it's a simple solution to this. Instead using an usual combination:

    location.hash = "";
    location.hash = _some_hash_string_
    

    use javascript below:

    var hashElement=document.getElementsByName(_some_hash_string_)[0];
    if(hashElement) {
        hashElement.scrollIntoView();
    } else { 
        // if the element is not found - scroll to top
        document.documentElement.scrollIntoView(); 
    }