我正在尝试使用src = http://www.domain.com/folder/从iFrame中访问scrollTop值,而包含iFrame的页面使用下面显示的代码http://sub-domain.domain.com/another-folder/,但我收到以下错误:
var stopval = $(parent.document).scrollTop();
错误:
Error: Blocked a frame with origin "http://www.domain.com" from accessing a cross-origin frame.
显然这是一个SOP问题,所以想知道是否有任何工作......解决这个问题的方法?我在网上搜索过但无法找到解决方案从iFrame页面获取scrollTop值而没有收到此错误。感谢
答案 0 :(得分:4)
正如fgshepard提到的问题可以使用window.postmessage解决,如下所示:
一个。在src = http://www.domain.com/folder/的iFrame中添加:
<script type="text/javascript">
window.addEventListener("message", listener, false);
function listener(event){
if ( event.origin !== "http://sub-domain.domain.com" )
return
console.log('Message Received : '+event.data);
}
</script>
B中。在包含http://sub-domain.domain.com/another-folder/下方iframe的页面中,添加:
<script type="text/javascript">
var win = document.getElementById("iframeid").contentWindow;
$(window).scroll(function(){
var wintop = $(window).scrollTop();
win.postMessage($(window).scrollTop(), 'http://domain.com');
});
</script>
以上代码应将包含iframe的页面中的scrollTop()值发送到iframe src页面。
答案 1 :(得分:0)
我认为你的回答大多是here解释的。您可以将document.domain
的值设置为当前域的后缀。
如果您的网页为http://sub-domain.domain.com/another-folder/
而您尝试使用Iframe http://www.domain.com/folder/
,则以下代码可以为您提供帮助:document.domain = 'domain.com'
。
你的情况完全相反。您的网页http://www.domain.com/folder/
正在评估来自http://sub-domain.domain.com/another-folder/
的内容。但看起来你不能document.domain = 'sub-domain.domain.com'
,因为它不是你当前域的后缀(但请尝试)。
答案 2 :(得分:0)
scrollTo()控制垂直和水平位置。希望这可能有用
parent.scrollTo(0,0);
答案 3 :(得分:-1)
如果您可以控制两个位置的文档,则可以使用window.postMessage来实现此目的。这允许您在文档和跨域之间传递消息,并提供一定程度的安全性。例如,在这种情况下,当您需要从父窗口获取scrollTop值时,您可以向它发送一条消息:
parentWindow.postMessage('scrollTop', targetOrigin, [...]);
父窗口将有一个可以响应信息的消息监听器:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
var response = null;
if (event.origin !== "http://example.org:8080") {
return;
}
if (event.data === 'scrollTop') {
response = $(document).scrollTop();
childWindow.postMessage(response, targetOrigin, [...]);
return response;
}
return false;
}
子窗口也有一个监听器:
window.addEventListener("message", receiveMessage, false);
然后,receiveMessage函数将使用收到的信息。
如果您想要更通用的解决方案,您父窗口的receiveMessage函数可以简单地响应以下结果:
response = $(document)[message]();
其中message将包含您有兴趣接收的任何jQuery调用。当然,还可以进行进一步的抽象。