Skip to content Skip to sidebar Skip to footer

Scroll A Cross-domain Child Iframe?

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,

Solution 1:

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.


Solution 2:

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.


Post a Comment for "Scroll A Cross-domain Child Iframe?"