栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript SecurityError:阻止了具有原始位置的框架访问跨域框架

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript SecurityError:阻止了具有原始位置的框架访问跨域框架

同源政策

您无法

<iframe>
使用Javascript访问其他来源的内容,如果可以的话,这将是一个巨大的安全漏洞。对于同源策略,浏览器会阻止脚本尝试访问来源不同的框架。

如果未保留地址的以下至少之一,则认为起源是不同的:

<protocol>://<hostname>:<port>/...

*如果要访问框架, *协议主机名端口 必须与您的域相同。

注意:众所周知InternetExplorer并不严格遵循此规则。

例子

尝试从中访问以下URL会发生以下情况

http://www.example.com/home/index.html

URL RESULT http://www.example.com/home/other.html       -> Success http://www.example.com/dir/inner/another.php -> Success http://www.example.com:80         -> Success (default port for HTTP) http://www.example.com:2251       -> Failure: different port http://data.example.com/dir/other.html       -> Failure: different hostname https://www.example.com/home/index.html:80   -> Failure: different protocolftp://www.example.com:21          -> Failure: different protocol & port https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname

解决方法

即使同源策略阻止脚本访问源不同的站点的内容,但是
如果您同时拥有两个页面,则可以使用

window.postMessage
及其相对
message
事件
在两个页面之间发送消息来 解决此问题
,如下所示:

  • 在您的主页中:
    let frame = document.getElementById('your-frame-id');

    frame.contentWindow.postMessage(/any variable or object here/, 'http://your-second-site.com’);

的第二个参数

postMessage()
可以是
'*'
指示对目的地的起点没有任何偏好。在可能的情况下,应始终提供目标来源,以避免泄露您发送到任何其他站点的数据。

  • 在您的
    <iframe>
    (包含在主页中):
    window.addEventListener('message', event => {// importANT: check the origin of the data! if (event.origin.startsWith('http://your-first-site.com')) {     // The data was sent from your site.    // Data sent with postMessage is stored in event.data:    console.log(event.data); } else {    // The data was NOT sent from your site!     // Be careful! Do not use it. This else branch is    // here just for clarity, you usually shouldn't need it.    return; }

    });

此方法可以在 两个方向
上应用,也可以在主页上创建侦听器,并从框架接收响应。相同的逻辑也可以在弹出窗口中实现,并且基本上也可以在主页中(例如使用

window.open()
)生成的任何新窗口中实现,没有任何区别。

在禁用同源策略 您的 浏览器

关于该主题已经有了一些很好的答案(我刚刚找到了它们),因此,对于可能的浏览器,我将链接相对答案。但是,请记住, 禁用同源策略只会影响 您的
浏览器
。此外,运行禁用了同源安全设置的浏览器会授予 任何 网站访问跨域资源的权限,因此,
这是非常不安全的,如果您不确切知道自己在做什么(例如,出于开发目的),则永远不要这样做

  • Google Chrome
  • Mozilla Firefox
  • Safari
  • Opera
  • Microsoft Edge: not possible
  • Microsoft Internet Explorer


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380235.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号