My situation:
I have 2 websites:
website 1
____________
| |
| website 2 | --- loading inside iframe
|____________|
Note: Using different domains
Job: In website 1, I have an array like:
var scrollTopPoints = [100, 900, 500, 300, 630];
I want to animate the points in the array in the <iframe>
(so website 2 will be modified).
Error message I received:
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://domain1.com" from accessing a frame with origin "http://domain2.com". Protocols, domains, and ports must match.
I tried to fix the problem with postMessage()
, like in in this SO post.
But I still cant modify the scrollTop
of the <iframe>
.
Some test code (maybe not related)
Website 1 (including the iframe):
<script src="/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
$('iframe').on('scroll', function() {
console.log('scrolled.');
});
function receiveMessage(event)
{
console.log(event.data);
}
addEventListener("message", receiveMessage, false);
$("iframe").contents().children().animate({ scrollTop: 100 }, 100);
});
</script>
Website 2:
<div style="height:300px;background:#333;"></div>
<div style="height:300px;background:#555;"></div>
<div style="height:300px;background:#777;"></div>
<div style="height:300px;background:#999;"></div>
<script src="jquery.min.js"></script>
<script>
$(window).on('scroll', function() {
parent.postMessage("This is a message", "*");
});
</script>
Note that I used this as test code. I now see that:
- I posted the wrong way (website 2 ---> website 1)
- The part of the array is not defined here.
Another edit: The main problem is how to do animate the iframe with postmessage communication, because I can't access the iframe content directly when it has another domain.
Last edit: Problem solved
I used postmessage the wrong way. The code that did work for other visitors to this question:
Website 1 (parent)
<iframe id="frame" src="http://localhost/postmessage_test/" frameborder="0"></iframe>
<script src="/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function() {
var scrollPoint = 100;
var targetFrame = $('#frame')[0];
targetFrame.onload = function() {
targetFrame.contentWindow.postMessage(scrollPoint, '*');
};
});
</script>
Website 2 (child)
<div id="postMessage" style="height:30px;"></div>
<div style="height:1500px;background:#333;"></div>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
var key = e.message ? "message" : "data";
var data = e[key];
window.scrollTo(0, data);
},false);
});
</script>
Thanks for all the help related to my post.