triggering events in an iframe
Recently, I had need to change the value of a select menu in an iframe from the outer page containing the iframe. There was a change
event listener that had been added in the iframe’s JavaScript:
1 2 3 4 |
// iframe's JavaScript document.getElementById('menu').addEventListener('change', function() { console.log('change callback triggered!'); }); |
I wanted to change the value of the select menu and for the change
callback
to happen. As you can see, the iframe didn’t use jQuery to set the change
event handler, so I couldn’t do the following:
1 2 3 4 5 |
// doesn't trigger callback function! var iframe = $('iframe'); var iframe_select = iframe.contents().find('select#menu'); iframe_select.val(value); iframe_select.trigger('change'); |
That didn’t work. I could inspect the select menu after this code ran and its
value was definitely updated, but the change
callback never happened.
What ended up working for me was the following code. I’d never used
createEvent
, initUIEvent
, and dispatchEvent
before, so I thought I’d
share:
1 2 3 4 5 6 7 |
// parent page's JavaScript var iframe = $('iframe'); var iframe_select = iframe.contents().find('select#menu'); iframe_select.val(value); var ev = iframe[0].contentWindow.document.createEvent('UIEvents'); ev.initUIEvent('change', true, true, window, 1); iframe_select[0].dispatchEvent(ev); |
comments powered by Disqus