Home > OS >  Is there a way to inject an external style sheet into an iframe?
Is there a way to inject an external style sheet into an iframe?

Time:07-07

I have a website that has an editor on one side of the page and an iframe on the left. Currently, the iframe is updated automatically on keyup when you enter HTML code inside the editor. I would like the code entered in the editor to have default styling within the iframe. Because it's a game where you enter HTML tags the items that will be styled are the default tags (h1, p, div, etc). Because of this, I can't have styling within the HTML document because it will style the items on the entire page rather than just items in the iframe. I would like to have an external style sheet that is contained within the iframe so I can style the tags without affecting 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" ></iframe>

JS

editor.addEventListener('keyup',()=>{
    var html = editor.textContent;
    iframe.src = "data:text/html;charset=utf-8,"   encodeURI(html)   "<style>"   style.textContent   "</style>";
  });

CodePudding user response:

Yes sure why not. They are 2 different documents.

var style = "h1{color:red}";

var iframe = document.querySelector("iframe");

var html = "<h1>hello world</h1>";
iframe.src = "data:text/html;charset=utf-8,"   encodeURI(html)   "<style>"   style   "</style>";
h1 {
  color: blue;
}

iframe {
  border: 1px solid black;
}
<h1>hello world</h1>
<iframe src="" frameborder="0" ></iframe>

If you insist on using external css, then instead of <style> tag add <link rel="stylesheet" href="https://example.com/style.css"> to the HTML of the iframe.

  • Related