Is it possible to load a cross domain child iframe and scroll it to a certain section?
Say, for instance, I wanted to reference a question on Stack Overflow, and using JavaScript, scroll it to the particular part of the page where the question is, and maybe overlay a highlight, or something.
My hack would be to load the iframe with a huge height, like really really tall, and then scroll it by just moving the position.
That sucks though, is there a better way?
Is it possible to load a cross domain child iframe and scroll it to a certain section?
Say, for instance, I wanted to reference a question on Stack Overflow, and using JavaScript, scroll it to the particular part of the page where the question is, and maybe overlay a highlight, or something.
My hack would be to load the iframe with a huge height, like really really tall, and then scroll it by just moving the position.
That sucks though, is there a better way?
Share Improve this question asked Jun 2, 2012 at 18:28 RandallBRandallB 5,5856 gold badges36 silver badges48 bronze badges 6- 1 If you want to overe the cross-domain protections (which prevents you from reading or writing the content), the simplest is to fetch server-side the page and include it this way. – Denys Séguret Commented Jun 2, 2012 at 18:34
- @dystroy , this is the way to go unless SO policies allows scraping. – Jashwant Commented Jun 2, 2012 at 18:43
- @JeffreySweeney of course if there are known names that's possible. – Denys Séguret Commented Jun 2, 2012 at 18:45
- 1 So, doesnt even allow iframing :) – Jashwant Commented Jun 2, 2012 at 18:46
- Yes, that's true too... server side inlining seems the way to go but I would check on meta it's wele before doing it. – Denys Séguret Commented Jun 2, 2012 at 18:49
2 Answers
Reset to default 2One approach to this is to set a negative top on the iframe, then set it taller than you need it.
For example, if you want to display it scrolled to 100px
, then set top:-100px
and add 100px to the height.
Then all you need is for the top part of the iframe to be hidden, e.g. off the top of the screen or underneath other elements (using z-index).
This would probably be bined with scrolling="no"
on the iframe element.
If the iframe is loaded from a different origin domain, there is very little you can do to interact with it. The browsers enforce a cross origin security that will not let you manipulate the iframe content directly. If you have some control about the content that is being loaded into the iframe you could use postMessage
function.
The postMessage
API seems to be fairly well supported. You can take a look at the specification and a demo.
This blog post seems to have a pretty good overview of approaches to the problem.
Your hack of just setting the height of the iframe is an interesting idea, but you would have to know just how long it needs to be so it would only work if you know something about the content you want to display.