stompJs出现TextEncoder is not defined解决方法

2,349 阅读1分钟

介绍

上周在实现一个聊天的业务时,测试发现该功能在IE和Edge下是不能实现。在查看报错之后发现报错 Unhandled promise rejection ReferenceError: 'TextEncoder' is not defined。 原来是stompJs使用了TextEncoder方法,但IE和Edge的JavaScript运行环境不支持该方法。 我找到了以下几种方法。 只针对SPA应用

正文

In NodeJs

如果你的NodeJs版本升到了v11,那么node的运行环境是支持TextEncoder方法的。但是如果你的项目的nodeJs版本低于v11,可以安装moduletext-encodin

$ npm install text-encoding

加在入口文件

// These have been added in NodeJS v11, so good idea is to check first
if (typeof TextEncoder !== 'function') {
    const TextEncodingPolyfill = require('text-encoding');
    window.TextEncoder = TextEncodingPolyfill.TextEncoder;
    window.TextDecoder = TextEncodingPolyfill.TextDecoder;
}

WebSocket

因为第一种方法解决了我的方法,所以一下方法没有去实践。

据了解有两个备用库websocketws可以使用。

  • websocket

$ npm install websocket

在全局对象global中添加

Object.assign(global, { WebSocket: require('websocket').w3cwebsocket });

  • ws

$ npm install ws

Object.assign(global, { WebSocket: require('ws') });