base64 encoding and decoding, native js

Native atob and btoa method:

In fact, starting with IE10 + browser, all the browser native in the Base64 encoding and decoding methods, not only for the browser environment, Service Worker environment can also be used.

Method name is atob and btoa, specific syntax is as follows:

1) Base64 decoding

The syntax is (the browser):  

var decodedData = window.atob(encodedData);

Or (browser or js Worker thread):

var decodedData = self.atob(encodedData);

E.g:

window.atob('emhhbmd4aW54dQ==');
 
// 返回:'zhangxinxu'

atob this method name at first glance, very strange, I do not know what the word meant. We can be understood as A to B, that is, from A to B. B here refers to the Base64 it? Ha ha ha, congratulations! guessed wrong! A means is Base64, anti, B is an ordinary character, common sense is low, commonly known as low B. So we are so memory, Low B, Low B, B Low said he was an ordinary character, A is Base64, and the first letter of correspondence is opposite.

Therefore, atob Base64 character to represent ordinary characters, which is Base64 decoding.

2) Base64 encoding

The syntax is (the browser):

var encodedData = window.btoa(stringToEncode);

Or (browser or js Worker thread):

var encodedData = self.btoa(stringToEncode);

E.g:

window.btoa('zhangxinxu');
 
// 返回:'emhhbmd4aW54dQ=='

This method btoa name at first glance, very strange, I do not know what the word meant. We can understand to A to B, that is, from B to A. So what B means that A refers to what it? And a method as atob, B refers to the low B ordinary string, A refers to the Base64 character.

Therefore, btoa method represents a low B ordinary characters to Base64 character, which is Base64 encoded.

ps:

Moment, there are still many PC project also needs to be compatible IE9, so we can specifically for these browsers reintroduction period ployfill script or a JS file.

Actual use, we can use IE conditional comments seamless. It is embedded in HTML code for the following section:

[If IE] represents all the IE browser, since IE10 + browser has abandoned support for the famous IE conditional comments is, Chrome and other browsers themselves do not support this IE private grammar, therefore, very natural, the above paragraph script introduced only in effective next IE9- browser. And we would hope only IE8, IE9 browser introduced ployfill, so just perfect convergence.

That is native support atob and btoa methods browser is HTML think some do not care about the comments, and do not support atob btoa the browser IE9 and below will load our base64-polyfill.js, the browser also supports window. btoa and window.atob this syntax.

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 246 original articles · won praise 51 · views 330 000 +

Guess you like

Origin blog.csdn.net/weixin_41829196/article/details/104032296