简体   繁体   中英

How can I inject large HTML file into iFrame?

I need to inject HTML into an iFrame dynamically. How can I "wrap" this html so that it will be properly escaped so I can pass it as a js var?

Here is what I have. So far it looks as if the first line of the html is stored in 'content' but then the rest is displayed in the browser window (outside the frame).

    <script type="text/javascript" language="javascript">
     var content = <%=Model.Html%>;
    var doc = document.getElementById("testFrame");
    if (iframe.contentDocument)
        doc = iframe.contentDocument; // For NS6
    else if (iframe.contentWindow)
        doc = iframe.contentWindow.document; // For IE5.5 and IE6
    // Put the content in the iframe
    doc.open();
    doc.writeln(content);
    doc.close();
</script>  

I have an iFrame on the page with

id = "testFrame"

<%=Model.Html%> Contains the HTML that I am trying to inject. Its includes some JS inline. This document is what I need to "wrap".

Have you considered using.src attribute of your iframe?

var doc = document.getElementById("testFrame");
doc.src = <%=Model.html%>;

Or you also could refresh it with AJAX and use doc.src=req.responseText;

Since this is a ASP.NET MVC application I just created a new action (GetHtml) that returns Html.

I set the src of the iFrame to this new action. Like so:

<iframe id="testFrame" name="testFrame" src ="<%= Url.Action("GetHtml","MyController", new{href = Model.Href}) %>>" width="100%" height="600">
    <p>
        Your browser does not support iframes.
    </p>
</iframe>

Controller:

public ActionResult GetHtml()
{
...
return Content(htmlContent, "text/html");
}

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