kivi
kivi

Reputation: 1

scripts add iframe content do not have user agent style in chrome

chrome version: 58

Normally, form will have a user agent style margin-bottom: 1em;

<!DOCTYPE html>
<html>
  <head>
    <title>test</title>
    <meta charset="utf-8" />
  </head>

  <body>
    <form action="#">
      First name:<br><input type="text" name="firstname" value="Mickey"><br>
      Last name:<br><input type="text" name="lastname" value="Mouse"><br><br>
      <input type="submit" value="Submit"></form>
      <div>hello world</div>
  </body>

</html>

with user agent style

but when I add content to iframe by scripts, the form does not have style margin-bottom: 1em;

    <!DOCTYPE html>
    <html>
        <head>
            <title>clack test</title>
            <meta charset="utf-8" />
        </head>
        <body>
            <script>
                var iframe = document.createElement("iframe");
                iframe.id = 'iframe';
                iframe.width = '100%';
                iframe.height = '886';
                iframe.setAttribute("scrolling", "no");
                iframe.setAttribute("frameborder", "0");
                document.body.appendChild(iframe);

                // find the iframe's document and write some content
                var idocument = iframe.contentDocument;
                idocument.open();
                idocument.write("<!DOCTYPE html>");
                idocument.write("<html>");
                idocument.write("<head></head>");
                idocument.write('<body><form action="/demo/demo_form.asp\">First name:<br><input type="text" name="firstname" value="Mickey"><br>Last name:<br><input type="text" name="lastname" value="Mouse"><br><br><input type="submit" value="Submit"></form><div>hello world</div></body>');
                idocument.write("</html>");
                idocument.close();
            </script>
        </body>
    </html>

without user agent style

I wonder how to let the user agent style work in iframe. Thanks

Upvotes: 0

Views: 154

Answers (1)

user8780079
user8780079

Reputation:

script = document.getElementById("js");
iframe = document.createElement("iframe");
document.body.appendChild(iframe);
iframe.appendChild(script);
<script id="js">
  // the script you want to inject
  alert("Injected");
  console.log("Injected");
</script>

try using something like this

HTML:

<script id="js">
 // the script you want to inject 
</script>

JS:

script = document.getElementById("js");
iframe.appendChild(script);

I made a Weave at LiveWeave.

Upvotes: 1

Related Questions