我永远不会在我自己的代码中执行以下操作,但是作为<iframe>
可以使用数据 URI的,以下可能是一个解决方案。
window.encodeURIComponent
你的代码来创建一个字符串。
%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
然后将其转换为数据 URI并在您的 src 上设置为src<iframe>
,然后附加到文档。当我使用字符串文字时,我在下面
转义引号。'
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
示例小提琴