Window.scrollto javascript call to uiwebview misbehaving

I have several uiwebviews with significant amounts of text. when you call the javascript window.scrollto (as well as window.scroll) on the webviews, they scroll to the wrong location. for example I want to scroll to 12000, but the webview will scroll to 10149 each time instead. while the other one will scroll to 10250. Another one I want to scroll to 22000 or so will scroll to 20230 each time instead.

this only happens on the device, not in the simulator.

I am making a call to webViewDidFinishLoad.

I have tried making the call several times with no better results. it seems that whatever value a particular scrollable webview is viewing is the furthest that can go when using the scrollto call. no problem when you specify a lower value for scrolling. it's easy, if you pass that magic number, whatever it is for this webview, it won't go further.

any input would be appreciated

+2


source to share


2 answers


One reason for this can happen if you are referencing images in your markup without explicitly declaring their dimensions. Your images may not have finished loading when webViewDidFinishLoad: is called. The browser first lays out the page using the estimated image size. Once the image is loaded and the browser can determine its actual dimensions, it will reflow the page, which can lead to an increase in the overall page height. If your call to window.scrollTo comes before this recalculation, you may be trying to scroll to the bottom of the page.

If this is what is happening in your case, you can solve it by declaring the sizes of your img tags explicitly in your markup or CSS.



If for some reason you cannot predict the image sizes ahead of time, you can defer your window.scrollTo request until the images have finished loading by registering a javascript event handler for window.onload that does not fire until all images have finished loading. In your event handler navigate to your window.location.href file to some fake url like "app: imagesFinishedLoading". In UIWebViewDelegate, you can implement webView: shouldStartLoadWithRequest: navigationType: intercept this navigation, cancel it, and then make your call to window.scrollTo.

+1


source


so I found that the problem was because I was calling the scrollTo function too early (although I called it in webViewDidFinishLoad, which I assumed would only be called after the page was fully loaded, and visually, at least it looked). I set a timer so the scrollTo method would call 300 milliseconds later and that took care of it.



+1


source







All Articles