5

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?

RandallB
  • 5,415
  • 6
  • 34
  • 47
  • 1
    If you want to overcome 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 Jun 02 '12 at 18:34
  • @dystroy , this is the way to go unless SO policies allows scraping. – Jashwant Jun 02 '12 at 18:43
  • @JeffreySweeney of course if there are known names that's possible. – Denys Séguret Jun 02 '12 at 18:45
  • 1
    So, doesnt even allow iframing :) – Jashwant Jun 02 '12 at 18:46
  • Yes, that's true too... server side inlining seems the way to go but I would check on meta it's welcome before doing it. – Denys Séguret Jun 02 '12 at 18:49
  • Blah... I think I'm going to do the height thing. I don't want to scrape people's content unless they're cool with it, so if I end up doing this, I'll just start with tall iframes, and then maybe offer an API for people who are cool with it via postmessage. – RandallB Jun 05 '12 at 23:48

2 Answers2

1

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.

martineno
  • 2,623
  • 17
  • 14
0

One 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 combined with scrolling="no" on the iframe element.

Jordan Morris
  • 2,101
  • 2
  • 24
  • 41