Jquery accessing $(parent.document).scrollTop from iFrame and SOP
html, iframe, javascript, jquery
Solution
As fgshepard mentioned problem can be solved using window.postmessage as follows:
A. In the iFrame with src= http://www.domain.com/folder/ add:
<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. In the page containing the iframe at http://sub-domain.domain.com/another-folder/ just below the add:
<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>
The above code shall send the scrollTop() value from the page containing the iframe to the iframe src page.
Problem
I am trying to access scrollTop value from within an iFrame with src= http://www.domain.com/folder/ while the page containing the iFrame is at http://sub-domain.domain.com/another-folder/ using the code shown below yet I am getting the following error: ``` var stopval = $(parent.document).scrollTop(); ``` Error: ``` Error: Blocked a frame with origin "http://www.domain.com" from accessing a cross-origin frame. ``` Obviously it is an SOP issue, so was wondering if there were any work arounds...approaches to solve this issue? I've searched the web but couldn't find a solution getting scrollTop value from the iFrame page without receiving this error. Thanks