From 5afa7c289e5197f141161c1f5ee85d68694c1e34 Mon Sep 17 00:00:00 2001 From: WenheLI Date: Tue, 4 Feb 2020 08:24:45 +0800 Subject: [PATCH] Fix saving at webworker (#2647) BUG This PR is to fix the bug while saving models at webworker env. (https://github.com/tensorflow/tfjs/issues/2643) Note: Under webworker, we can only save models via IndexedDB. Maybe we should mention it at the docs? --- tfjs-core/src/io/indexed_db.ts | 2 +- tfjs-core/src/io/local_storage.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/tfjs-core/src/io/indexed_db.ts b/tfjs-core/src/io/indexed_db.ts index 2ce5a8ce0f..35fada1ffc 100644 --- a/tfjs-core/src/io/indexed_db.ts +++ b/tfjs-core/src/io/indexed_db.ts @@ -57,7 +57,7 @@ function getIndexedDBFactory(): IDBFactory { 'is not a web browser.'); } // tslint:disable-next-line:no-any - const theWindow: any = window; + const theWindow: any = window || self; const factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB; diff --git a/tfjs-core/src/io/local_storage.ts b/tfjs-core/src/io/local_storage.ts index 50adc72144..beab813902 100644 --- a/tfjs-core/src/io/local_storage.ts +++ b/tfjs-core/src/io/local_storage.ts @@ -38,6 +38,7 @@ const MODEL_METADATA_SUFFIX = 'model_metadata'; */ export function purgeLocalStorageArtifacts(): string[] { if (!env().getBool('IS_BROWSER') || + typeof window === 'undefined' || typeof window.localStorage === 'undefined') { throw new Error( 'purgeLocalStorageModels() cannot proceed because local storage is ' + @@ -119,7 +120,8 @@ export class BrowserLocalStorage implements IOHandler { constructor(modelPath: string) { if (!env().getBool('IS_BROWSER') || - typeof window.localStorage === 'undefined') { + typeof window === 'undefined' || + typeof window.localStorage === 'undefined') { // TODO(cais): Add more info about what IOHandler subtypes are // available. // Maybe point to a doc page on the web and/or automatically determine @@ -307,6 +309,7 @@ export class BrowserLocalStorageManager implements ModelStoreManager { env().getBool('IS_BROWSER'), () => 'Current environment is not a web browser'); assert( + typeof window === 'undefined' || typeof window.localStorage !== 'undefined', () => 'Current browser does not appear to support localStorage'); this.LS = window.localStorage;