Passing rendered html to a javascript function - javascript

I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?

Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.

I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly

You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");

Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'

Related

knockout.js best way to bind html string in textarea with line breaks

I've got the html string that I'd like bind with knockout.js and display it in textarea, and of course allow submitting it after some editing. What is the proper way to achieve that?
When I use HTML binding, I can bind one <br/> two string and it displays the same in textarea, but after submitting, I get the encoded string one<br/>two, which isn't too bad as I can handle it later, but there's still the line breaks issue.
Basically I'd like to preserve:
original line breaks
original html text
Now, when I pass:
<html>
<body>
using both value and html binding, in knockout I get script exception, as new lines are not handled. Special characters are encoded as well:
Content: ko.observable("<html>
<body>
Any ideas?
You might want to use btoa to encode the actual value so that no munging goes on in submission. Then you would use atob to decode on the server. Here's a little demo that lets you see how various treatments of html come out.
ko.applyBindings({stuff: ko.observable('<h1>Foo</h1>hi\nthere')});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<textarea data-bind="value:stuff"></textarea>
<pre data-bind="text:stuff"></pre>
<hr />
<pre data-bind="html:stuff"></pre>
<hr />
<pre data-bind="text: btoa(stuff())"></pre>

&amp code javascript are not being replaced with &

My code:
window.open("http://www.facebook.com/sharer.php?u="+urlToShare+"&"+"t="+"test","_blank", "width=700, height=400");
On the resulting URL '&' should be replaced with '&', right? But, it isn't being replaced.
No.
An & which you want to express as data in an HTML document should (with a few exceptions such as being inside a <script> or when followed by a space) be expressed as &. It will then be interpreted by the browser as & after the HTML is parsed.
In this case, you have JavaScript (which is not HTML) and a URL (which is also not HTML) so there is no HTML to parse so the HTML parsing rules that would read & as & do not apply.
Not in HTML. Character references are not allowed everywhere:
In certain cases described in other sections, text may be mixed with
character references.
When the HTML parser finds a <script> tag, it switches the tokenizer to the script data state.
Unlike the data state, the script data state doesn't have character references.
So just use & instead of &.
<!-- This is HTML -->
<script>
alert('&');
</script>
However, you would need & in XHTML, because in XML the parser doesn't have different behaviors depending on the element.
<!-- This is XHTML -->
<script>
alert('&');
</script>
But using & in JS code is undesirable, so you can wrap the code in a CDATA section
<!-- This is XHTML -->
<script><![CDATA[
alert('&');
]]></script>

<br> is removed when I alert() the content of PRE tag

I want to show the content of this <pre> tag using alert():
<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain: shirzadi.ir<br>ascii: shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks: (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c: es372-irnic<br>admin-c: es372-irnic<br>tech-c: to52-irnic<br>bill-c: to52-irnic<br>nserver: wres1.irpowerweb.com<br>nserver: wres2.irpowerweb.com<br>last-updated: 2014-01-16<br>expire-date: 2017-10-08<br>source: IRNIC # Filtered<br><br>nic-hdl: es372-irnic<br>person: Ehsan Shirzadi<br>e-mail: ehsan.shirzadi#gmail.com<br>address: Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone: +985117688851<br>fax-no: +989155066372<br>source: IRNIC # Filtered<br><br>nic-hdl: to52-irnic<br>org: Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail: sales#mihannic.com<br>source: IRNIC # Filtered<br><br></pre>
when I read this content using xx = $('pre').text() and then alert(xx), the is no <br> but when I hard code this content in a variable and alert() I can see them. What is the problem here? finally I want to split the contents by <br>
Try $('pre').html() instead of text(). This should preserve < br > as well as other tags / html entities.
Edit
For completeness, as gillesc said, < br > and other tags will be stripped in alert() (since it does not support inner html). Therefore combination of .html() and replace method is required. Newline can be replaced by \n. Full code would look like this:
xx = $('pre').html().replace(/<br>/g, "\n");
alert(xx);
text() will strip the tags out so use html() instead but alert doesn't support tags so you will need to convert your <br/> before sending it to laert
See this post on how to do just that.
HTML Tags in Javascript Alert() method
Using text() keeps only the inner text, not the HTML markup.
Use html() and eventually replace each captured <br /> by the JS new line character, like said here : How replace HTML <br> with newline character "\n"
Make Like This
<pre id="MyID">This is Test <br /> This is test</pre>
and javascript code
<script>
alert(document.getElementById('MyID').innerHTML);
</script>

Handling single quote in JavaScript and jQuery

I am trying to display values in a div of JSP dynamically. The below $('#test${i}${j}') selects a div dynamically as I want, but the HTML part is creating issue for me. ${column} is just a value, for example, accountant, financeMR, etc.:
<c:out value="<script>$('#test${i}${j}').html(${column}); </script>" escapeXml="false" />
In the above I get an error which says "accountant is undefined", etc. The reason being there is no single quote (') wrapping ${column} (in HTML). However, if I try the below, it works in all cases except the cases where the ${column} value contains a single quote. For example, Mng'r:
<c:out value="<script>$('#test${i}${j}').html('${column}'); </script>" escapeXml="false" />
How can I resolve it?
The Apache commons lang library provides escape utilities: http://commons.apache.org/proper/commons-lang/
This should do the trick:
StringEscapeUtils.escapeEcmaScript(inputString);

Issue in JavaScript retrieve information

Premise: I've started to study javascript and the DOM and I have this HTML fragment:
<body>
<div id="Area_T10" class="abAdArea">
<script src="http://ad.dc2.adtech.de/addyn/3.0/831/***1644116***/0/744/ADTECH;" language="javascript1.1" type="text/javascript"></script>
<script>
** -- My script var n = **
</script>
</div>
</body>
I want to retrieve the number "16644116" from the div but I cannot figure out how to do it.
Can you help?
Best Regards.
Domenico
I am assuming you want to extract the number from the script source URL.
First step, get the script source value:
var src = document.getElementsByTagName('script')[0].src;
Then, if you're familiar with regular expressions, you should be able to create a pattern to extract that value.
Extract the URL from the attribute using whichever DOM manipulation technique you prefer (perhaps a library)
Use a regular expression to extract the desired portion of the URL

Categories