解决微信小程序不支持TextEncoder/TextDecoder对象

问题描述:在使用小程序开发者工具开发小程序中使用到了CRC算法,其中有一行代码使用到了TextEncoder对象,在开发工具中一切正常,到手机上会报出错误错误如下:
MiniProgramError
TextEncoder is not defined
ReferenceError: TextEncoder is not defined

解决办法:

// 报错代码
const encoder = new TextEncoder("utf-8");
const data = encoder.encode(inputString);

方法一:使用兼容写法

//TextEncoder
unescape(encodeURIComponent(inputString)).split("").map(val => val.charCodeAt());
//TextDecoder
decodeURIComponent(escape(String.fromCharCode(...['需解码的内容替换'])));

方法二:引入库

GitHub地址-EncoderDecoderTogether.min.js

小程序里直接require()引入,全局就有TextEncoder / TextDecoder 了。

// app.js
require('path/to/EncoderDecoderTogether.min.js')

或者使用NPM安装,安装方式见文档

GitHUb地址-FastestSmallestTextEncoderDecoder

这个库只支持utf-8编码,其他编码的话可以看看这个

Github地址-text-encoding

你可能感兴趣的:(微信小程序学习之路,微信小程序,小程序)