I dynamically load an iframe with JavaScript. After it's loaded, how can I make it scroll down a specific number of pixels (ie. after the page in the iframe has loaded, how can I make the iframe scroll by itself to the a specified region of the page?)
To scroll an iframe with JavaScript, we can use the scrollTo method. const myIframe = document. getElementById("iframe"); myIframe. onload = () => { myIframe.
Calling a parent JS function from iframe is possible, but only when both the parent and the page loaded in the iframe are from same domain i.e. example.com , and both are using same protocol i.e. both are either on http:// or https:// .
Add scrolling="no" attribute to the iframe.
An iframe does not have a scroll method, the document of the iframe does - you need to reference the inner document rather than your <iframe> tag.
You can use the onload
event to detect when the iframe has finished loading, and there you can use the scrollTo function on the contentWindow of the iframe, to scroll to a defined position of pixels, from left and top (x, y):
var myIframe = document.getElementById('iframe'); myIframe.onload = function () { myIframe.contentWindow.scrollTo(xcoord,ycoord); }
You can check a working example here.
Note: This will work if both pages reside on the same domain.
Inspired by Nelson's comment I made this.
Workaround for javascript Same-origin policy with regards to using.ScrollTo( ) on document originating on an external domain.
Very simple workaround for this involves creating a dummy HTML page that hosts the external website within it, then calling .ScrollTo(x,y) on that page once it's loaded. Then the only thing you need to do is have a frame or an iframe bring up this website.
There are a lot of other ways to do it, this is by far the most simplified way to do it.
*note the height must be large to accommodate the scroll bars maximum value.
--home.html
<html> <head> <title>Home</title> </head> <frameset rows="*,170"> <frame src=body.htm noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no"> <frame src="weather.htm" noresize=yes frameborder=0 marginheight=0 marginwidth=0 scrolling="no"> </frameset> </html>
--weather.html
<html> <head> <title>Weather</title> </head> <body onLoad="window.scrollTo(0,170)"> <iframe id="iframe" src="http://forecast.weather.gov/MapClick.php?CityName=Las+Vegas&state=NV&site=VEF&textField1=36.175&textField2=-115.136&e=0" height=1000 width=100% frameborder=0 marginheight=0 marginwidth=0 scrolling=no> </iframe> </body> </html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With