javascript encodeURIComponent returning additional characters - javascript

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.

Related

How to recover from decodeURI(encodeURIComponent(originalString))?

I have some legacy code (pre-React) that encodes part of a URL with encodeURIComponent before calling history.push() on the https://www.npmjs.com/package/history module in order to navigate to that URL.
history.push() inside history.js then uses decodeURI to decode the entire URL partially (decodeURI only decodes the same characters that encodeURI encodes)
this partially decoded location.pathname ends up in ReactRouter where useParams() gives me the partially decoded URL component back again.
Now I'm stuck with a partially decoded URL component which I cannot use. I need it fully decoded.
I can't use decodeURIComponent on the partially decoded string, because the original string might contain a %, in which case this % will already be decoded in the partially decoded string and this would cause decodeURIComponent to crash with a Uncaught URIError: URI malformed.
My options seem to be:
use unescape to fully decode the partially decoded string (it doesn't complain about the single %) even though its use is discouraged (why?)
manually re-encode any % (that isn't followed by a digit and a subsequent hex character) back to %25 and then run the result through decodeURIComponent
Are there any less ugly solutions that I haven't thought of yet ?
EDIT : I was asked for examples of what I meant by partially decided string
const original = 'A-Za-z0-9;,/?:#&=+$-_.!~*()#%';
const encodedURIComponent = encodeURIComponent(original); // "A-Za-z0-9%3B%2C%2F%3F%3A%40%26%3D%2B%24-_.!~*()%23%25"
console.log(decodeURIComponent(encodedURIComponent)); // "A-Za-z0-9;,/?:#&=+$-_.!~*()#%"
const partiallyUnescaped = decodeURI(encodedURIComponent); // "A-Za-z0-9%3B%2C%2F%3F%3A%40%26%3D%2B%24-_.!~*()%23%" - notice the '%25' at the end was decoded back to '%'
console.log(unescape(partiallyUnescaped)); // "A-Za-z0-9;,/?:#&=+$-_.!~*()#%"
//console.log(decodeURIComponent(partiallyUnescaped)); // error
EDIT 2: In case it can be of any help, here's a more realistic example of some of the characters our URL might contain, but because it's user generated, it could be anything really:
console.log( encodeURIComponent('abcd+%;- efgh')) ; // "abcd%2B%25%3B-%20efgh"
console.log( decodeURI(encodeURIComponent('abcd+%; -efgh'))) ; // "abcd%2B%%3B- efgh"
//console.log(decodeURIComponent(decodeURI(encodeURIComponent('abcd+%; -efgh')))); // Error: URI malformed

trailing "=" being trimmed in angular2 url

I have a problem in an angular2 project where I'm generating a URL to be sent to a user via email. The URL in the email needs to contain a special ID which is passed in the router as:
{ path: somepath/:id }
The user then clicks on the url which will be:
http://localhost/somepath/{id}
My problem is that the id can contain a trailing "=" character which gets automatically trimmed off when navigating to the url (and therefore making the ID now incorrect)
I have tried encoding the id before adding it to the url making the url:
http://localhost/somepath/XXX%3D
but the encoded "=" (%3D) still gets trimmed off.
Is there any reason why encoded url values are still being trimmed off and is there any way to prevent this?
Ok was just a massive oversight on my part....
I the actual id was being masked by a random encryption generator that includes symbols and usually ends in "=". What I didn't notice however, was that there was a ")" that was being included in a couple of cases as well, which does not get encoded and was causing everything after it to be trimmed off when loading the URL.
Ended up fixing it by replacing the ")" with a different symbol that doesn't get encoded but one that doesn't have another function in Angular2 (in this case a "*").

Encoding Request parameters for preventing Cross Site Scripting Attacks giving Encoded values in Omniture Report

I have encoding many request parameters in Javascript function to prevent Cross Site Scripting Attacks. After Encoding, all the special characters are appearing as corresponding encoded value in report. I want to encode the value to prevent attacks but want to capture the corresponding decoded values.
EncodeURIComponent(Hello+); Now it is neccesary to encode values to prevent attacks but I want to register the value as Hello+, not Hello%20 something.
To get + instead of %20, call replace on the output of encodeURIComponent:
str = encodeURIComponent(str).replace(/%20/g, '+');
However, I can't imagine the circumstance in which encodeURIComponent is the correct function to use to prevent XSS. Technically it will work (except inside single-quoted attribute values), but it will mangle the output. XSS only occurs in HTML, so I think you might want an HTML escaping function instead:
function escapeHtml(text) {
return text.replace(/[&"'<>]/g, function(c) {
return (
c == '&' ? '&' :
c == '"' ? '"' :
c == "'" ? ''' :
c == '<' ? '<' : '>'
);
});
}
I have many javascript functions on my jsp Pages. I am taking request parameters and assigning them to some variables. so if I replace the encoded value with the corresponding special character value, the problem still persist. you can test it by putting alert with some request parameter in the URL. On hitting Enter , the alert will popup. So with encoding corresponding () will be change to encoded values and alert will not appear. If I replace the encoded value with the (), the problem still persists.

Pass a parameter containing '%' in URL?

While passing my url, for example something:8000/something.jsp?param1=update&param2=1000&param3=SearchString%&param4=3 , I am getting following error:
Bad Request
Your browser sent a request that this server could not understand.
I know SearchString% which I need to pass as a parameter, has the issue. Then how to pass a
parameter containing '%' in URL??
Use %25 in place of %
In URLs % has a special meaning as an escape character
Special characters like (space) can be encoded like %20 (the ascii code for space/32 in hex)
Therefore a percent sign itself must be encoded using the hex code for % which happens to be 25
You can use http://www.asciitable.com/ to look up the appropriate hex code under the hx column
Alternatively, if you are doing this programatically (ie. with javascript) you can use the builtin function escape() like escape('%')
See this: Encode URL in JavaScript?
Basically you need to make sure the variables you are passing are encoded (the '%' character is a special character in URL encoding).
Any special characters - %,?,&, etc... need to be encoded. They are encoded with '%' and their hex number. So '%' should become '%25', '&' becomes '%26', etc.
Update: see When are you supposed to use escape instead of encodeURI / encodeURIComponent? for why you should avoid using escape.

Prevent Conversion of HTML Entities

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;
};

Categories