滚动跨域子iframe? [英] Scroll a cross-domain child iframe?

查看:160
本文介绍了滚动跨域子iframe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以加载跨域子iframe并将其滚动到某个部分?

Is it possible to load a cross domain child iframe and scroll it to a certain section?

比如说,我想在Stack Overflow上引用一个问题,并使用JavaScript,将其滚动到问题所在的页面的特定部分,并可能覆盖突出显示,或其他。

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.

我的黑客将是加载iframe有一个巨大的高度,就像真的很高,然后通过移动位置滚动它。

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?

推荐答案

如果从不同的原始域加载iframe,则几乎无法与其进行交互。浏览器强制执行跨源安全性,不允许您直接操作iframe内容。如果您对加载到iframe中的内容有一些控制权,则可以使用 postMessage 函数。

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.

postMessage API似乎是得到很好的支持。您可以查看规范演示

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.

你只是设置iframe的高度是一个有趣的想法,但你必须知道它需要多长时间,只有当您对要显示的内容有所了解时才会有效。

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.

这篇关于滚动跨域子iframe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆