why javascript protocol decode the URL automatically?

987 views Asked by At

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.

2

There are 2 answers

1
T.J. Crowder On BEST ANSWER

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>

0
Quentin On

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.