My website features an editor on one side and an iframe on the other. Currently, anytime HTML code is entered into the editor and a keyup event occurs, the iframe updates automatically. I am looking to add default styling to the code entered in the editor so that it displays with specific styles within the iframe. The challenge is that the game involves entering HTML tags like h1, p, div, which need to be styled separately but I don't want these styles to affect the entire page outside the iframe. To achieve this, I plan to implement an external style sheet contained within the iframe. This way, I can style the specific tags without impacting the rest of the index.html page.
<style>
* {
padding: 0;
margin: 0;
}
html {
display: flex;
justify-content: center;
}
h2 {
color: rgba(255, 255, 255, 0);
width: 300px;
height: 50px;
margin: 10px;
background-color: crimson;
}
</style>
<iframe src="" frameborder="0" class="iframe"></iframe>
JS
editor.addEventListener('keyup',()=>{
var html = editor.textContent;
iframe.src = "data:text/html;charset=utf-8," + encodeURI(html) + "<style>" + style.textContent + "</style>";
});