I would never do the following in my own code, but as an <iframe>
can use a data URI, the following could be a solution.
window.encodeURIComponent
your code to create a string.
%3C!DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Chead%3E%0A%3Cscript%3E%0Afunction%20copyText()%0A%7B%0Aalert('It%20is%20clicked')%3B%0A%7D%0A%3C%2Fscript%3E%0A%3C%2Fhead%3E%0A%3Cbody%3E%0A%0AField1%3A%20%3Cinput%20type%3D%22text%22%20id%3D%22field1%22%20value%3D%22Hello%20World!%22%3E%3Cbr%3E%0AField2%3A%20%3Cinput%20type%3D%22text%22%20id%3D%22field2%22%3E%0A%3Cbr%3E%3Cbr%3E%0A%3Cbutton%20onclick%3D%22copyText()%22%3ECopy%20Text%3C%2Fbutton%3E%0A%0A%3C%2Fbody%3E%0A%3C%2Fhtml%3E
Then convert this to a data URI and set as src on your <iframe>
, then append to document.
I escape quotes '
below as I'm using a string literal.
var ifrm = document.createElement('iframe'); // create
ifrm.src = 'data:text/html,' // convert to data URI, set src
+ '%3C!DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Chead%3E%0A%3Cscript%3E%0Afunction%20copyText()%0A%7B%0Aalert(\'It%20is%20clicked\')%3B%0A%7D%0A%3C%2Fscript%3E%0A%3C%2Fhead%3E%0A%3Cbody%3E%0A%0AField1%3A%20%3Cinput%20type%3D%22text%22%20id%3D%22field1%22%20value%3D%22Hello%20World!%22%3E%3Cbr%3E%0AField2%3A%20%3Cinput%20type%3D%22text%22%20id%3D%22field2%22%3E%0A%3Cbr%3E%3Cbr%3E%0A%3Cbutton%20onclick%3D%22copyText()%22%3ECopy%20Text%3C%2Fbutton%3E%0A%0A%3C%2Fbody%3E%0A%3C%2Fhtml%3E';
document.body.appendChild(ifrm); // append
Example fiddle