11

I create a JSoup Document which includes two <script type="application/javascript">/* .. */</script> elements.

The Issue: When I call .html() or .toString() JSoup will escape my JavaScript.

if (foo && bar) 

gets

if (foo &amp;&amp; bar)

Is it possible to configure JSoup to ignore <script> Elements while escaping??


This is (basically) how I create my jsoup document.

final Document doc = Document.createShell("");
final Element head = doc.head();
head.appendElement("meta").attr("charset", "utf-8");
final String myJS = ...;
head.appendElement("script").attr("type", "application/javascript").text(myJS);

My current workaround is to replace a placeholder with String.replace on .html(). But this is kinda hacky.

head.appendElement("script").attr("type", "application/javascript").text("$MYJS$");
String s = doc.html();
s = s.replace("$MYJS$", myJS);
1
  • I've updated my answer. Commented Aug 7, 2015 at 14:47

1 Answer 1

7

The outerHtmlHead method can no longer be overridden.

This is what I use:

head
    .appendElement("script")
    .attr("type","text/javascript")
    .appendChild(new DataNode(getJavaScript(),""));
2
  • I would have expected .text() to work. I feel like this is a bug. .text() shouldn't do html encoding. Commented Apr 12, 2018 at 10:51
  • @citizenconn When you want to display text in HTML, it must be encoded first, rather HTML mustn't be encoded. And JSoup simply handles scripts as being data in an element, that's just how it works -> no bug.
    – sjngm
    Commented Jun 16 at 17:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.