0

I am very new to iFrames.

I have a simple HTML and I want to wrap it in iFrames.HTML is as below.

<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
alert('It is clicked');
}
</script>
</head>
<body>

Field1: <input type="text" id="field1" value="Hello World!"><br>
Field2: <input type="text" id="field2">
<br><br>
<button onclick="copyText()">Copy Text</button>

</body>
</html>

Please help on how to wrap it using iFrames.

Thanks Gendaful

2

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

@Teemu I'd never do this in my own code.
@ryan biggest use of code like this is XSS. Second biggest use would be.. some form of live document writing? The premise behind it isn't so hard to follow though; have some data, save to file, open file in an iframe - but using the fact it is a data URI to skip the "save" step.
I found this old and ugly solution actually helpful and useful when I had an unfriendly script that was using the document.write function. Because I couldn't change the script and had to test it in a specific way, and because document.write can't be called from and outside script, I wrote the script tag into an IFrame like that. That shows that even the weirdest answers might be helpful one day. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.