Search code examples
javascripthtmleventsiframehashchange

Capture iFrame onhashchange event from the parent


I've being trying to capture the event onHashChange of an iFrame from his parent without success.

So basically I'm doing:

index.html - Approach 1:

iframeEl = document.getElementById('myiframeid');
iframeEl.addEventListener('hashchange', function() {
    alert('hash changed')
}, true);

index.html - Approach 2:

iframeEl = document.getElementById('myiframeid');
iframeEl.onhashchange = function() {
    alert('hash changed')
};

Regardless, none of the approaches work when I try to capture the iframe event from his parent, although if I try to run the code below from inside the iframe:

window.addEventListener('hashchange', function() {
    alert('hash changed')
}, true);

or

window.onhashchange = function() {
    alert('hash changed')
};

Both approaches will work.

Trouble is: I need to capture the hashchange event from the outside the iFrame.

Does anyones have a idea on how to handle it?

FYI: jQuery isn't an option.

Thanks in advance.


Solution

  • Let's say you want to test for hash changes on IframeElement.contentWindow, from the page that contains your <iframe>:

    //<![CDATA[
    // external.js - the page with your <iframe>
    var doc, bod, htm, C, E, T; // for use on other loads
    addEventListener('load', function(){ // window.onload sort of
    
    doc = document; bod = doc.body; htm = doc.documentElement;
    C = function(tag){
      return doc.createElement(tag);
    }
    E = function(id){
      return doc.getElementById(id);
    }
    T = function(tag){
      return doc.getElementsByTagName(tag);
    }
    var innerWindow = E('yourIframeId').contentWindow;
    var oldHash = innerWindow.location.hash.replace(/#/, '');
    innerWindow.addEventListener('hashchange', function(){
      console.log('#'+oldHash+' has been changed to #'+innerWindow.location.hash.replace(/#/, ''));
    });
    
    }); // end load
    //]]>