【发布时间】:2020-01-19 15:21:42
【问题描述】:
有没有办法绕过页面(域B)上的iframe(域A)尝试访问属性时出现的跨域安全错误window.top?
我想调用一个函数,即。 someFunc,属于域B,通过域A的iframe中的一个事件,在域B的上下文中。
例子:
a.com/index.html
<!DOCTYPE html>
<html>
<body>
<script>
var someFunc = t => document.querySelector("#test").text = t;
</script>
<span id="test">This is some dummy text.</span>
<iframe src="https://b.com/index.html"></iframe>
</body>
</html>
b.com/index.html
<!DOCTYPE html>
<html>
<body>
<button id="btn">Test</button>
<script>
document.querySelector("#btn").addEventListener("click", (e) => {
window.top.someFunc("This text has been changed through a cross-origin")
});
</script>
</body>
</html>
此示例在 Firefox 上引发以下错误:SecurityError: Permission denied to access property "someFunc" on cross-origin object
【问题讨论】:
-
没有......
-
这是您需要使用 postMessage 并在两个域上都有代码的地方。
-
我知道这一定看起来很傻,但我很欣赏这个答案,否则我可能不会找到 postMessage ......我稍后会写答案
标签: javascript iframe cross-domain postmessage