Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JSoup Document including JS?

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);
like image 859
boop Avatar asked Aug 03 '15 14:08

boop


Video Answer


1 Answers

The outerHtmlHead method can no longer be overridden.

This is what I use:

head
    .appendElement("script")
    .attr("type","text/javascript")
    .appendChild(new DataNode(getJavaScript(),""));
like image 67
user3300388 Avatar answered Sep 26 '22 02:09

user3300388