Skip to content

Instantly share code, notes, and snippets.

@mostlygeek
Created January 3, 2013 08:19
Show Gist options
  • Save mostlygeek/4441793 to your computer and use it in GitHub Desktop.
Save mostlygeek/4441793 to your computer and use it in GitHub Desktop.
Playing around with creating an iframe, and then adding content into it and being able to send messages back/forth to it. demo at: http://jsfiddle.net/mostlygeek/P7jqp/
/*
Was watching this talk: http://www.youtube.com/watch?v=y4lBEZTThvg
about iframes and JS ... so this will create a new iframe, inject new
HTML content into it and send it messages through the window.location.hash every second
*/
(function() {
el = document.getElementById('foo');
iframe = document.createElement('iframe');
iframe.src = "about:blank";
el.appendChild(iframe)
// the iframe has to be part of the DOM before we can access it...
iDoc = iframe.contentWindow.document;
iDoc.open('text/html', 'replace');
// stick in some content ... dynamically ... ohh
src = '<html><body><div id="out"><\/div><div id="message">--<\/div><script>'
+ 'var c=0; var c2=0; var el=document.getElementById("out"); '
+ 'var msgEl = document.getElementById("message");'
+ 'window.onhashchange = function() { el.innerHTML = "change #" + (c++) + ", time: " + window.location.hash; };'
+ 'function setMessage(msg) { msgEl.innerHTML = "last msg #" + (c2++) + ", time: " + msg; }'
+ '<\/script><\/body><\/html>';
iDoc.write(src);
iDoc.close();
var c = 0;
// this is dog ass slow... and it sort of triggers a fake refresh of the page
// let's not do this ... well we can use it to make the user's browser *really* slow
setInterval(function() {
iframe.contentWindow.location.hash = "" + (Date.now() / 1000);
}, 2500); // set high cause it is really annoying...
// this is really fast... 16ms = 60fps
setInterval(function() {
iframe.contentWindow.setMessage("" + (Date.now() / 1000));
}, 16);
})();
@adrianbenzo
Copy link

n

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment