IOS Safari doesn't scroll to snap in iframe

I have an HTML page with an iframe , the contents of which I need to scroll to a specific place on loading. My example works fine in most browsers except iOS Safari - this is the one I really need. It works in iOS Safari when loading the first page, but as a rule, after updating the iframe content is scrolled up.

I read about issues where redirects cause #anchorname , but that is not what happens in this case.

The real iframe content and the main page are in different domains. I can influence the contents of the iframe , but I have no control over it. It is also used for other purposes, so I would have a limited opportunity to do something custom that could prevent it.

Direct link here: https://s3.amazonaws.com/ios-iframe-test/iframe_test.html

Here is the parent content:

 <!DOCTYPE html> <html> <head> <title>test</title> <meta content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0" name="viewport"> <style type="text/css"> #root { position: relative; } #wrapper { height: 300px; width: 300px; overflow-x: hidden; overflow-y: scroll; position: relative; -webkit-overflow-scrolling: touch; } iframe { width: 100%; height: 100%; } </style> </head> <body> <h1>Why won't this iframe scroll to where I want?</h1> <div id="root"> <div id="wrapper"> <iframe src="https://s3.amazonaws.com/ios-iframe-test/iframe_content.html#scrolltome"></iframe> </div> </div> </body> </html> 

And here is the contents of the iframe :

 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body> <h1>Have some ipsum...</h1> <p> Lorem... (live example has much more here just to make the scrolling apparent) </p> <h1 style="color: red;"> <a name="scrolltome" id="scrolltome">This is where I want to scroll></a> </h1> <p> Lorem... </p> </html> 
+5
source share
1 answer

This is due to a Safari iOS bug in which the iframe expands to the height of its content. You can verify this using the Safari debugging desktop and run:

document.querySelector('iframe').offsetHeight

The solution is to reduce the height of the iframe body by placing the contents in a position: fixed container and letting it scroll.

For example, put the body contents in the <main> and set the style as follows:

  <html> <head> <style> main { position: fixed; top: 0; right: 0; bottom: 0; left: 0; padding: 10px; overflow-y: scroll; -webkit-overflow-scrolling: touch; z-index: 1; } </style> </head> <body> <main> <h1>Have some ipsum...</h1> <p>Lorem... (live example has much more here just to make the scrolling apparent)</p> <h1 style="color: red;"> <a name="scrolltome" id="scrolltome">This is where I want to scroll</a> </h1> <p> Lorem... </p> </main> </body> </html> 

This tells Safari that the iframe body is the same height as the page containing it, but its contents scroll. Now your anchors will work.

0
source

Source: https://habr.com/ru/post/1258944/


All Articles