Sometimes developers should resolve the task - how to connect site which is in <iframe> tag and the parent site using JavaScript. And how for example refresh something instantly in <iframe> when something done in the parent site? That was the problem in the past, but not now as we can use HTML5 features. Lets look on the next example with <ul> items!
- So on the parent site we have <ul> and can identify it as '.providers_list li', and by logic of interface there is some js events which insert or deleted <li> from that <ul>. And in the site which is in <iframe> we want to get text of that links which are there.
- Create 1 js file on the parent site and 1 js file in the site which will be in-buit in the parent site by <iframe id="mdtf_csp_frame">
- Insert in parents js file next code:12345678910jQuery(function () {var iframe = jQuery('#mdtf_csp_frame');setInterval(function () {var message=new Array();jQuery('.providers_list li').each(function (i, o) {message.push(jQuery.trim(jQuery(o).find('a').eq(0).text()));});iframe[0].contentWindow.postMessage(message.join(', '), '*');}, 2000);});
- After page loaded we start setInterval function which each 2 seconds check providers list <a> and get text from each of that link
- Then using HTML5 function postMessage we will send collected data to <iframe>
- In the site which is in the tag <iframe> we should use next code:123456789101112131415var onmessage = function (e) {var data = e.data;//var origin = e.origin;if (document.getElementById('textarea.wpbdp-field-14') !== null) {document.getElementById('textarea.wpbdp-field-14').readOnly = true;document.getElementById('textarea.wpbdp-field-14').innerHTML = data;}};if (typeof window.addEventListener != 'undefined') {window.addEventListener('message', onmessage, false);} else if (typeof window.attachEvent != 'undefined') {window.attachEvent('onmessage', onmessage);}
- wpbdp-14 is textarea in site which is in tag <iframe> and in which we adding new information each 2 seconds from the parent site list '.providers_list li'.
That is all. The same principle you can use for another cases ...
