I have a javascript function which takes a string as its parameter. This string is encoded (with %20 for spaces, %26 for ampersands, etc..).
function myFunction(theParam) {
alert(theParam); // outputs &
}
// called by the following link
<a href="#" onclick='myFunction("%26")'>Do something</a>
How do I stop this behavior? I want myFunction to receive %26 as the parameter and not the ampersand......
Your example alerts %26 as expected for me. (And then falls through to navigating to #. Remember to return false from a click handler to stop the link being followed.)
You would get an ampersand if you did it in a javascript: link:
Do something
as javascript: URLs are still URLs and undergo normal URL-escaping rules. Of course, you should never use a javascript: URL anyway.
Better, assign from JavaScript itself so you don't have to worry about HTML-escaping issues either:
Do something
document.getElementById('somethingdoer').onclick= function() {
myFunction('%26');
return false;
};
Related
I'm passing the company name to an onclick event. Some company names have apostrophes in them. I added '.Replace("'", "'")' to the company_name field. This allows the onclick event to fire, but the confirm message displays as "Jane&# 39;s Welding Company".
<span class="ui-icon ui-icon-refresh"></span>
<script type="text/javascript">
function Actionclick(url, companyName)
{
if (confirm('This action will activate this company\'s primary company ('+companyName+') and all of its other subsidiaries. Continue?'))
{
location.href = url;
};
};
EDIT
The confirm message shows the &# 39; in the message rather than the '. When I typed it out here, it replaced the &# 39; with a '. Added spaces so that wouldn't happen. I want to know the best way to pass it to my onclick event and also properly display it in the message without doing multiple replaces (if there is a better way).
There are two options as I see it.
If you wrap the parameters in quotes (") instead of apostrophes/single quotes (') then you shouldn't need to escape it at all. HTML encoding will take care of encoding any quotes (if they are in the string) and the apostrophe's won't be a problem. Though, as the javascript is already wrapped in quotes, you will need to backslash escape your quotes. eg:
onclick="return Actionclick(\"<%= Url.Action("Activate", new {id = item.company_id}) %>\", \"<%= Html.Encode(item.company1.company_name) %>\");"
Backslash escape the company name as it's only the final javascript string that needs the apostrophe escaped, not the HTML. eg:
onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "\\'")) %>');"
You've got a JavaScript string literal inside an HTML attribute value.
So you would need to first JS-encode the value (replacing the ' with \' and \ with \\), then HTML-encode. Currently you are HTML-encoding the ' (which would be ineffective, since the browser would decode it back to an apostrophe before the JS engine saw it)... and then HTML-encoding it again, leaving it literally meaning '.
Use a JSON encoder to turn a string (or any other value type) into a JavaScript literal.
However. Writing JavaScript in a string utterly sucks. Keeping track of multiple layers of escaping isn't something the mind is good at. So don't do it. Avoid inline event handler attributes at all times. Instead, use static script and assign handlers from JavaScript itself, using unobtrusive scripting.
<a class="dangerous fg-button fg-button-icon-solo ui-state-default ui-corner-all"
href="<%= Server.HTMLEncode(Url.Action("Activate", new {id = item.company_id})) %>"
title="This action will activate this company's primary company (<%= Server.HTMLEncode(companyName) %>) and all of its other subsidiaries."
>
<span class="ui-icon ui-icon-refresh"></span>
</a>
(I'll use jQuery since you have it in your tags:)
<script type="text/javascript">
$('.dangerous').click(function() {
return confirm(this.title+' Continue?');
});
</script>
However note that this is an abuse of <a>. Actions that make an active change to something should never be sent, or be allowed to be received, as a GET request. You should instead use a button that submits a POST request (either directly as a form, or via AJAX). (You should also consider using ASP.NET's built-in controls instead of templating the values in, to avoid having to call HTMLEncode quite so much.)
See this classic WTF for one way in which this can bite you.
I just encountered this 5 years later so I'll share what worked for me.
Check out HttpUtility.JavaScriptStringEncode on MSDN
You can use this to encode the string on the server side when setting the property's value. This will produce the unicode representation of the apostrophe - "\u0027" which can be passed in to the JavaScript onclick.
For the original example:
item.company1.company_name = HttpUtility.JavaScriptStringEncode("Jane's Welding Company");
will become
"Jane'\u0027s Welding Company"
A note on HttpUtility.JavaScriptStringEncode - You can choose to specify a boolean to encode the string with double quotation marks (bool addDoubleQuotes). However, since this string will be used as a parameter to a JavaScript function, you do not want the extra quotes.
I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.
I´m working with a .js referring to a form.
In a function it sets the form's action and then submit it.
document.forms[0].action = "FileController.do?action=genFile&fileType="+ft+"&answType="+at;
document.forms[0].submit();
The problem is that answType's value sometimes has an "&" on it, like "M&M", so when I try to get that value like this:
String answer = request.getParameter("answType");
I only get the first "M" and lost the rest of the value.
I know that's because parameters are separated by "&".
But is there a workaround for this?
I can't change the original data.
Thank's
encodeURIComponent(string) will convert characters with special meaning in URLs (such as &) to their escape sequences.
For some reason, I am getting additional code in my encoded URI's with javascript encodeURIcomponent function, namely %25 character:
My function is:
function twit_click() {
var u="https://www.website.com/<?php echo $_SESSION['id'];?>";
var t="sometext";
window.open('http://www.twitter.com/share?url='+encodeURIComponent(u)+'&text='+encodeURIComponent(t),'twitsharer','toolbar=0,status=0,width=626,height=436');
return false;
}
when I click the text and call twit_click() function, I get the following URL:
http://twitter.com/intent/tweet?text=sometext&url=https%253A%252F%252Fwww.website.com%252Fuserid
as opposed to what it should be:
http://twitter.com/intent/tweet?text=sometext&url=https%3A%2F%2Fwww.website.com%2Fuserid
am I missing something? It is adding in additional "25" characters which would imply I have % in my URI which I clearly do not.
Remove the "www" from "www.twitter" and it works.
http://jsfiddle.net/tzkpz/
Twitter must be re-encoding the URL when it redirects from www.twitter.com to twitter.com, hence the double encoding.
i have a long String. With some German characters and lots of new lines tabs ect..
In a Selectbox user can select a text, on change i do
document.getElementById('text').value=this.value;
But this fails. I just get a "unterminated string literal" as error in JavaScript.
I think i should clean the string.
How can i do it in JavaScript?
Its not because of that code, there is syntax error somewhere in your javascript file.
For example, in one of your previous question's answer
alert("yes link clicked);
You could see, there is " is missing after clicked, which could cause unterminated string literal error. Fix it like
alert("yes link clicked");
As I cannot judge from your code, you might want to check what this in this.value refers to, e.g. using an alert("debug: " + this.value) .
Other than that, you might want to use encodeURI() for converting umlauts and other special characters to hexadecimal notation. If your page's content-type is set to UTF-8 special characters will then display correctly.