微信小程序之兼容

文章介绍了在微信开发者工具中能正常运行的ArrayBuffer到字符串以及字符串到ArrayBuffer的转换方法,但在真机环境中由于TextDecoder和TextEncoder未定义导致的问题。提供了一种简单的兼容性解决方案,即定义TextDecoder和TextEncoder函数,实现decode和encode方法,以确保在微信小程序中能够正常工作。
摘要由CSDN通过智能技术生成

ArrayBuffer转换字符串

const ab2Str = function(arrayBuffer:ArrayBuffer):string{
	const textDecoder = new TextDecoder();
    const data = textDecoder.decode(arrayBuffer);
    return data;
}

TextDecoder方法在微信开发者工具中是可以正常运行的,但是在真机中,报错:TextDecoder没有定义
最简单兼容做法:定义TextDecoder函数,实现decode方法,并支持中文

(function (global) {
    /**
     * 兼容TextDecoder
     */
    if (typeof global.TextDecoder !== 'function') {
        function _TextDecoder() {}
        _TextDecoder.prototype.decode = function (arrayBuffer) {
            // @ts-ignore
            return decodeURIComponent(escape(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer))));
        };
        // @ts-ignore
        global.TextDecoder = _TextDecoder;
    }
})(this || window || globalThis);

字符串转换ArrayBuffer

const str2Ab = function(str:string):ArrayBuffer{
	const textEncoder = new TextEncoder();
    const data = textEncoder.encode(str);
    return data;
}

TextEncoder方法在微信开发者工具中是可以正常运行的,但是在真机中,报错:TextEncoder没有定义
最简单兼容做法:定义TextEncoder函数,实现encode方法

(function (global) {
    /**
     * 兼容TextEncoder
     */
    if (typeof global.TextEncoder !== 'function') {
        function _TextEncoder() {}
        _TextEncoder.prototype.encode = function (str) {
            var data = unescape(encodeURIComponent(str))
                .split('')
                .map(val => val.charCodeAt(0));
            return typeof Uint8Array == 'function' ? new Uint8Array(data) : data;
        };
        // @ts-ignore
        global.TextEncoder = _TextEncoder;
    }
})(this || window || globalThis);

微信小程序更多兼容方法,请查看资源:我的资源

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光速度的进程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值