开发者

How can I inject large HTML file into iFrame?

开发者 https://www.devze.com 2023-03-16 11:19 出处:网络
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?

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/java开发者_如何学Cscript" 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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号