0

I need to inject some HTML, an <iframe> and some script content including <script> tags. However I'm having some issues with my approach. It seems that the closing </script> tag is not being rendered as a string literal and is being parsed by the page, this means that the <script> block that contains my function is being closed prematurely:

Example:

<script type="text/javascript">
function loadBookingForm($) {
    var str = <%= string.Format("'{0}';", this.IframeHtml) %>;
    $('#booking-form').text(str).html();
}
</script>

Which gets rendered as:

<script type="text/javascript">
function loadBookingForm($) {
    var str = '<iframe src="https://www.example.com/?noframe=true&skipHeaderFooter=true" style="width:100%;height:1000px;border:0px;background-color:transparent;" frameborder="0" allowtransparency="true" onload="keepInView(this);"></iframe><script>function keepInView(item) {if((document.documentElement&&document.documentElement.scrollTop)||document.body.scrollTop>item.offsetTop)item.scrollIntoView();}
</script>
';;$('#booking-form').text(str).html();}

As you can see, the closing script tag from the IframeHtml is closing the parent script block which causes the call to set the #booking-form html to fail.

I'm escaping newlines/carriage returns and HtmlDecoding the string in the code behind:

public string IframeHtml
{
    get
    {
        return HttpUtility.HtmlDecode(this.CurrentBookingForm.IframeHtml)
              .Replace("\n", string.Empty)
              .Replace("\r", string.Empty)
              .Replace("'", "\"");
    }
}

How can I inject both markup and script content into the targeted <div> element?

DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • Not sure if it's really clear from the dupe, but you have to split the closing script tag, as in something like `var s = '';` etc. or create an actual script element with `createElement('script')`. This is a common problem, and there are many solutions. – adeneo Dec 01 '14 at 12:24
  • @adeneo Creating a `script` element won't work in this scenario as I don't have absolute control over what's coming in the `IframeHtml`. I guess I could apply some formatting in the code behind, as you say, splitting the script tag though this is very ugly – DGibbs Dec 01 '14 at 12:26
  • There is no other way to do it, Google, Facebook and others still do it this way, either by splitting the closing tag string, or creating proper elements. – adeneo Dec 01 '14 at 13:03

0 Answers0