允许同源不允许我访问顶部对象的属性



我在example1.com页面中有以下代码:

<iframe src='//example2.com/embed.html' sandbox="allow-same-origin allow-modals allow-scripts allow-top-navigation allow-top-navigation-by-user-activation">

在我的embed.html

中有以下代码
<script>
try { 
document.write('top url: ' + top.location.href)
}
catch (e) { 
document.write('error' + e);
}
</script>

我得到错误:

SecurityError: Blocked a frame with origin "https://example2.com" from accessing a cross-origin frame.

我只想获得top对象的属性,我在我的iframe代码中使用标签allow-same-origin。这个标签不允许我以同源方式运行iframe吗?如果不是,为什么我们有那个标签?

example1.comexample2.com是不同的域,因此您有CORS(跨域资源共享)的问题,但没有内容安全策略。CORS仅允许在相同域或域与其子域之间进行直接访问。
你不能在跨域iframe中获得top.location.href属性,但是如果allow-top-navigation出现在sandox属性中或者sandbox不存在,你可以设置它:top.location.href = 'https://any_domain.com/path.html'

sandbox属性不能帮助绕过CORS限制,它只能对iframe中的功能施加额外的限制。

你可以使用window.postMessage()方法在页面和嵌入其中的iframe之间进行跨域通信。

最新更新