简体   繁体   中英

Escape Base64 String in URL?

For some reason I need to put a Base64 encoded string in the URL, ie

<script>
    var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>

The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error:

SyntaxError: unterminated string literal

Apparently there are charactors in the Base64 string requires escaping. However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation.

So how to make this work then?

If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. Below is a link to a base64 library for Javascript that you must load in.

http://www.webtoolkit.info/javascript-base64.html

You maybe also need a library to access the z attribute in your url. I would recommend this:

https://github.com/allmarkedup/purl

Just in case it helps, here is a short JS code requiring no dependency:

String.prototype.base64EncodeUrl = function () {
    var str = this;
    str = window.btoa(unescape(encodeURIComponent( str )));
    return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};

String.prototype.base64DecodeUrl = function () {
    var str = this, str_pad = (str + '===');
    str = str_pad.slice(0, str.length + (str.length % 4));
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    return decodeURIComponent(escape(window.atob( str )));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM