4

I am confused about why javascript protocol decodes the encoded URL, for example:

    <a href="javascript:myFunction('%3DcDO4w67epn64o76');">press</a> 
    function myFunction(id)
    {
        alert(id); //it will generate =cDO4w67epn64o76
    }

I am using these strings in encryption and decryption.

Please provide me with a real reason and a solution (the reason is very important for me), I know I can replace the (=) sign, but I am afraid of the rest of the encoded strings to be decoded also by the wrapper.

Note: in php, the GET, REQUEST Global variables, the url is decoded automatically.

naktinis
  • 3,957
  • 3
  • 36
  • 52
mina
  • 141
  • 1
  • 10

2 Answers2

3

Because it's in an href attribute, where URLs are expected, so the browser is "normalizing" the URI-encoding of the "URL" (which is using the javascript pseudo-scheme).

You can put it in a different attribute and then get that, like so:

function myFunction(element) {
  console.log(element.getAttribute("data-value")); //it will generate =cDO4w67epn64o76
}
<a href="javascript:;" onclick="myFunction(this)" data-value="%3DcDO4w67epn64o76">press</a> 

...although I discourage using onclick="..." handlers. Instead:

function linkHandler(e) {
  console.log(this.getAttribute("data-value"));
  e.preventDefault();
}


var links = document.querySelectorAll("a[data-value]");
Array.prototype.forEach.call(
  links,
  function(link) {
    link.addEventListener("click", linkHandler, false);
  }
);
<a href="javascript:;" data-value="%3DcDO4w67epn64o76">press</a>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • your answer is perfect for me till now but in [wiki](https://en.wikipedia.org/wiki/URL_normalization) , normalization will be applied by decoding unreserved encoded characters , and equal sign here is reserved . ! – mina Dec 20 '16 at 12:24
1

A URL using the javascript: scheme is still a URL.

You've attempted to store a URL in a JavaScript string in a URL.

When decoding the outside URL into JavaScript, the percent encoded characters are decoded.

To do what you are attempting you need to convert any special characters (like %) in the JavaScript to URL encoding:

<a href="javascript:myFunction('%253DcDO4w67epn64o76')%3B">test</a>

You should only use this for creating bookmarklets though.

If you want to run JavaScript when something is clicked, then use a click event handler. You could use an onclick attribute, but addEventListener in the modern approach (for values of modern equal to "not the 1990s").

Likewise, if you aren't linking somewhere, don't use a link. Use a button instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335