Scroll a cross-domain child iframe?

2020-04-11 13:21发布

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?

1条回答
Viruses.
2楼-- · 2020-04-11 14:02

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.

查看更多
登录 后发表回答