1

I want to do the following within rails. In a textfield of my db, there is the following html / javascript:

<script type="text/javascript">
  document.write('<div id="test"></div>');
</script>

I want to append the contents of this field into the head-tag of the DOM, so the inserted js will be executed.

In my rails erb-view, I have the following:

<script type="text/javascript">
  var code = "<%= @ticket.code %>"; // Content of codesnippet above
  $('head').append(code);
</script>

However I get some the following rendered output of the view:

var code = "&lt;script type=&quot;text/javascript&quot;&gt;
  document.write('&lt;div id=&quot;test&quot;&gt;&lt;/div&gt;');
&lt;/script&gt;"; 

Error message: unterminated string literal

I tried to gsub linebreaks and other ways of escaping, but I've got no clue, what actually is the best way to escape it. How can I get it correclty escaped and inserted into the DOM?

Thanks for your help!

1 Answer 1

1

I believe rails 3 comes with JQuery so why not just use:

$(document).onload(function()
{ 
    document.write('<div id="test"></div>');
});

and I believe on var code you should do the following:

var code = "<%= escape_javascript(@ticket.code.html_safe) %>"
Sign up to request clarification or add additional context in comments.

3 Comments

using html_safe is producing another problem: var code = "<script type="text/javascript"> document.write('<div id="test"></div>'); </script>"; The quotation marks now make the variable declaration end too soon.
@agieche then try var code = "<%= escape_javascript(@ticket.code.html_safe) %>"
Yeah, this worked smoothly. Thanks! Please edit your answer, so I can mark it as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.