javascript 访问 iframe 跨域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48031823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:45:26  来源:igfitidea点击:

Accessing Iframe Cross Origin

javascripthtmliframe

提问by Sanoj Sen

I have an HTML and an iframe inside it. when I try to access iframe contents it shows error like this.

我在里面有一个 HTML 和一个 iframe。当我尝试访问 iframe 内容时,它会显示这样的错误。

" Uncaught DOMException: Blocked a frame with origin "http://parattapayyan.surge.sh" from accessing a cross-origin frame.
    at http://parattapayyan.surge.sh/test.html:14:24
(anonymous) @ test.html:14 "

how some chat companies like "intercom" and etc, accessing iframe from external server and components inside iframe..?

一些聊天公司(如“对讲机”等)如何从外部服务器和 iframe 内的组件访问 iframe ..?

回答by Sanoj Sen

When Site A tries to fetch content from Site B in a frame, by default, Site B's pages are not accessible due to security reasons(Read this :: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy); But using the Access-Control-Allow-Origin header site B can give cross-origin access to specific requesting origins.

当站点 A 尝试在框架中从站点 B 获取内容时,默认情况下,由于安全原因,站点 B 的页面不可访问(阅读此内容 :: https://developer.mozilla.org/en-US/docs/Web/安全/同源策略);但是使用 Access-Control-Allow-Origin 标头站点 B 可以提供对特定请求源的跨源访问。

Site B can serve its pages to Site A with the following response header:

站点 B 可以使用以下响应标头向站点 A 提供其页面:

Access-Control-Allow-Origin: http://www.siteA.com

Without site B doing this, you won't be able to access site A in a frame.

如果站点 B 不这样做,您将无法在框架中访问站点 A。