Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 messaging multiple instance

i have a script like this

function resizeCrossDomainIframe(id, other_domain) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', function (event) {
        if (event.origin !== other_domain) return; // only accept messages from the specified domain
        if (event.data === "reload") top.location.reload(); // If child page sends reload request - reload it without any questions asked 
        if (isNaN(event.data)) { //If this isn't integer than it is alert
            alert(event.data); // Show alert if not integer
        } else {
            var height = parseInt(event.data) + 5; // add some extra height to avoid scrollbar
            iframe.height = height + "px";
            alert(event.data);
        }
    }, false);
}

what it does is dynamically resizes iframe. Now On a first iframe page I just get one alert, but in within iframe page i have links and when I go to second page I see 2 alerts, when I go to third page - i get 3 alerts, 4th link trigger 4 alerts etc...

In each iframed page I am calling parent to resize like:

<body class="settingspage" onload="parent.postMessage(document.body.scrollHeight, '<?php echo $_SESSION['SESS_ACCESSING_FROM']; ?>');">

I tried to clear the "event" array, but I still get Alerts, but this time they are empty, but the number of alerts equals the number of link-clicks within the iframe ?

Why is this ?

like image 781
Peter Avatar asked Feb 07 '13 12:02

Peter


1 Answers

The problem is, every time you click on a link in the iframe, the load event is fired.

So you bind your message event every time a link is clicked. On first time everything is correct, because you binded it once, on the second time you get two alerts, because you bound it twice, and so on...

So the solution is to remove the 'message'event on unload of iframe.

For this reason you have to clean your code a bit:

var listener = function (event) {

    if (event.data === "reload") top.location.reload(); // If child page sends reload request - reload it without any questions asked 
    if (isNaN(event.data)) { //If this isn't integer than it is alert
        alert(event.data); // Show alert if not integer
    } else {
        var height = parseInt(event.data) + 5; // add some extra height to avoid scrollbar
        iframe.height = height + "px";
        alert(event.data);
    }
};

then you have your functions which you call onLoad and onUnload.

function iframeOnLoad(id) {
    var iframe = document.getElementById(id);
    window.addEventListener('message', listener, false); 
}

function iframeOnUnload(id) {
    var iframe = document.getElementById(id);
    window.removeEventListener('message', listener, false); 
}
like image 163
Sam Avatar answered Oct 14 '22 18:10

Sam