Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
IE11 TextEncoder compatibility workaround
  • Loading branch information
esouthren authored Sep 11, 2019
commit 124b49f7ae077410b293e45b352ecd2f8303b92b
26 changes: 20 additions & 6 deletions tfjs-core/src/platforms/platform_browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,19 @@
* limitations under the License.
* =============================================================================
*/

import {ENV} from '../environment';
import {Platform} from './platform';

export class PlatformBrowser implements Platform {
private textEncoder: TextEncoder;

constructor() {
// According to the spec, the built-in encoder can do only UTF-8 encoding.
// https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder
this.textEncoder = new TextEncoder();
// Workaround for IE11 compatibility
// More info: https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
if (window.TextEncoder) {
this.textEncoder = new TextEncoder();
}
}

fetch(path: string, init?: RequestInit): Promise<Response> {
Expand All @@ -36,11 +39,22 @@ export class PlatformBrowser implements Platform {

encode(text: string, encoding: string): Uint8Array {
if (encoding !== 'utf-8' && encoding !== 'utf8') {
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
throw new Error(
`Browser's encoder only supports utf-8, but got ${encoding}`);
}
if (window.TextEncoder) {
return this.textEncoder.encode(text);
} else {
// Workaround for IE11 compatibility
const utf8 = unescape(encodeURIComponent(text));
const result = new Uint8Array(utf8.length);
for (let i = 0; i < utf8.length; i++) {
result[i] = utf8.charCodeAt(i);
}
return result;
}
return this.textEncoder.encode(text);
}

decode(bytes: Uint8Array, encoding: string): string {
return new TextDecoder(encoding).decode(bytes);
}
Expand Down