简体   繁体   中英

Why my iframe treats html content as text

Why iframe is treating my html content as text content.

Question: i want to render whole html with its tags, not as a text.

Below image shows my problem:

在此处输入图像描述

My code:

 $('#resultBtn').off('click'); $('#resultBtn').on('click',function(){ var html = '<p id="pclick">Click me to see Alert</p>' var javascript = `document.querySelector('#pclick').on('click',function(){ alert('clicked me'); })`; var bodyContent = html +`<script>${javascript}<\/script>`; $("#result_iframe").contents().find("body").html(`${bodyContent}`); });
 #result_iframe{ width: 400px; height: 200px; background:#eaeaed; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="resultBtn">see Result</button> <iframe id="result_iframe" frameborder="0"></iframe>

I am not an expert but I understand that you cannot pass JS in text after reading the document.
In the editor here it doesn't work, I don't know why, but in a test file it worked.
Try this (JS en parent).

  <button id="resultBtn">see Result</button>
   <iframe id="result_iframe" frameborder="0"></iframe>
   <script>
     var button = document.getElementById("resultBtn");
     var iframe = document.getElementById("result_iframe");

     button.onclick = function(){
       iframe.contentDocument.body.innerHTML = "<p onclick='window.parent.showAlert()'>Click Me</p>"
     }
     function showAlert(){
       alert("Hi");
     }
   </script>

This code is attempting to add HTML content to an iframe :

$("#result_iframe").contents().find("body").html(`${bodyContent}`);

However, adding text nodes or HTML elements to an iframe is not supported. From the HTML5 spec for iframe :

4.8.5 The iframe element

Content model:
Nothing

And here's what Nothing means in this context:

When an element's content model is nothing, the element must contain no Text nodes (other than inter-element whitespace) and no element nodes.

Given that adding content to an iframe is not supported, it's probably a good idea to use a different method.

Semed, you codes working fine. Make sure your script was written after jquery insert.

$('#resultBtn').off('click');
$('#resultBtn').on('click',function(){
  var html = '<p id="pclick">Click me to see Alert</p>'
  var javascript = `document.querySelector('#pclick').on('click',function(){
alert('clicked me');
})`;
  var bodyContent = html +`<script>${javascript}<\/script>`;


  $("#result_iframe").contents().find("body").html(`${bodyContent}`);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM