JSFiddle - React, Tailwind, and code Playground
by JAAulde
HTML
<div id="theDiv"></div>
JavaScript
/* Library builder */
var detachedExecution = ( function()
{
var aLibrary, iframe, sandboxDocument, sandboxHead;
aLibrary = [];
iframe = document.createElement( 'iframe' );
iframe.src = 'javascript:false';
iframe.style.display = 'none';
document.body.appendChild( iframe );
sandboxDocument = iframe.contentWindow.document;
sandboxDocument.write( '<html><head></head><body></body></html>' );
sandboxDocument.close();
sandboxHead = sandboxDocument.getElementsByTagName( 'head' )[0];
iframe.contentWindow.detachedWindow = window;
return {
add: function( sScriptBody, bRunNow )
{
index = aLibrary.length;
aLibrary.push( sScriptBody );
if( typeof bRunNow === 'boolean' && bRunNow )
{
this.run( index );
}
return index;
},
run: function( index, args )
{
if( typeof aLibrary[index] === 'string' )
{
var oScriptElement = sandboxDocument.createElement( 'script' );
oScriptElement.appendChild( sandboxDocument.createTextNode(
'window.func' + index + ' = new Function( "$div", ' + JSON.stringify( aLibrary[index] ) + ' );'
) );
sandboxHead.appendChild( oScriptElement );
iframe.contentWindow['func' + index].apply( iframe.contentWindow, args );
}
}
};
}() );
/* Random class using the lib */
var Foo = function(){};
Foo.prototype.bar = function()
{
var sScript, libIndex;
sScript = '\
console.dir( arguments );\
alert( arguments.length );\
$div.html( "Worked!" );\
apple = "orange";\
alert( "detached: " + detachedWindow.apple );\
alert( "local: " + window.apple );\
alert( "local not doted: " + apple );\
detachedWindow.f();\
';
libIndex = detachedExecution.add( sScript );
...