首页 > 其他分享 >polyfill base64 atob and btoa

polyfill base64 atob and btoa

时间:2024-08-12 14:06:52浏览次数:4  
标签:function string polyfill base64 bitmap atob root 255

 

https://github.com/MaxArt2501/base64-js

 

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], function() {factory(root);});
    } else factory(root);
// node.js has always supported base64 conversions, while browsers that support
// web workers support base64 too, but you may never know.
})(typeof exports !== "undefined" ? exports : this, function(root) {
    if (root.atob) {
        // Some browsers' implementation of atob doesn't support whitespaces
        // in the encoded string (notably, IE). This wraps the native atob
        // in a function that strips the whitespaces.
        // The original function can be retrieved in atob.original
        try {
            root.atob(" ");
        } catch(e) {
            root.atob = (function(atob) {
                var func = function(string) {
                    return atob(String(string).replace(/[\t\n\f\r ]+/g, ""));
                };
                func.original = atob;
                return func;
            })(root.atob);
        }
        return;
    }

        // base64 character set, plus padding character (=)
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        // Regular expression to check formal correctness of base64 encoded strings
        b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;

    root.btoa = function(string) {
        string = String(string);
        var bitmap, a, b, c,
            result = "", i = 0,
            rest = string.length % 3; // To determine the final padding

        for (; i < string.length;) {
            if ((a = string.charCodeAt(i++)) > 255
                    || (b = string.charCodeAt(i++)) > 255
                    || (c = string.charCodeAt(i++)) > 255)
                throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");

            bitmap = (a << 16) | (b << 8) | c;
            result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63)
                    + b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
        }

        // If there's need of padding, replace the last 'A's with equal signs
        return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
    };

    root.atob = function(string) {
        // atob can work with strings with whitespaces, even inside the encoded part,
        // but only \t, \n, \f, \r and ' ', which can be stripped.
        string = String(string).replace(/[\t\n\f\r ]+/g, "");
        if (!b64re.test(string))
            throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");

        // Adding the padding if missing, for semplicity
        string += "==".slice(2 - (string.length & 3));
        var bitmap, result = "", r1, r2, i = 0;
        for (; i < string.length;) {
            bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12
                    | (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));

            result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255)
                    : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255)
                    : String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
        }
        return result;
    };
});

 

标签:function,string,polyfill,base64,bitmap,atob,root,255
From: https://www.cnblogs.com/angdh/p/18354836

相关文章

  • base64加密解密,中文乱码问题
    base64加密解密,中文乱码问题通常的方法是通过window.btoa()方法对源数据进行编码,然后接收方使用window.atob()方法对其进行解码,从而得到原数据.由于btoa方法仅支持ASCII编码,我们在转换中文的时候就需要先将中文转换为ASCII字符序列,再通过btoa进行base64编码,......
  • js、php实现前后端数据的base64编码和解码
    客户要求密码必须加密后再传送。javascript代码的加密函数:<scriptlanguage='javascript'>functionutf16to8(str){varout,i,len,c;out="";len=str.length;for(i=0;i<len;i++){c=str.charCodeAt(i);if(......
  • 接口文档,jwt,base64编码解码
    Ⅰ接口文档【一】接口文档了解#作为后端,接口写完了--->接口给前端使用 -登录接口:username,password,code#写接口的人负责写接口文档 -如何写?-写在哪?#通常在公司中: 1使用world编写,放在公共平台上2使用MD编写3第三方平台编写:showdoc -http......
  • JS之File对象与base64字符串之间的相互转换
    File对象有两种形态,在请求时为:控制台输出为:从formData中获得fileList对应的File对象,并转换为base64字符串,再转换回File对象,代码示例如下:constfileList=uploadFormData.get("fileList");console.log(fileList);constreader=newFileReader();reader.readAsDataURL(......
  • es6-promise-polyfill 自己实现promise.js
       https://github.com/lahmatiy/es6-promise-polyfill/blob/master/promise.js  (function(global){////CheckfornativePromiseandithascorrectinterface//varNativePromise=global['Promise'];varnativePromiseSupported=NativePr......
  • smartforms 转 PDF 并 BASE64 加密
      DATA:lv_fmname          TYPE tdsfname,       ls_control_param   TYPE ssfctrlop,       ls_job_output_info TYPE ssfcrescl,       ls_output_options  TYPE ssfcompop,       l_fm               TYPE......
  • .net-base64转ofd文件转pdf转图片后压缩打包
    最近有需求从第三方获取到ofd文件后,需要转pdf,1.目前看的有一个免费的插件,需要安装程序包FreeSpire.PDF 安装后,直接引用//odf文件地址stringpath=@"D:\OFD\20240725\吴天.ofd";OfdConverterconverter=newOfdConverter(path);//path......
  • binascii.Error:无效的 base64 编码字符串:数据字符数 (41) 不能多于 1 4 的倍数
    我正在尝试使用py-vapid、pywebpush和django-push-notifications通过Webpush发送通知。当我尝试从django管理网站发送测试通知时,我在控制台中收到此回溯日志:|InternalServerError:/djangoadmin/push_notifications/webpushdevice/......
  • 视野修炼-技术周刊第93期 | polyfill.io 投毒
    欢迎来到第93期的【视野修炼-技术周刊】,下面是本期的精选内容简介......
  • js上传base64
    <!DOCTYPEhtml><html><head><title>UploadImage</title></head><body><inputtype="file"id="fileInput"><buttononclick="uploadImage()">UploadImage</button&g......