Created
September 5, 2022 05:16
-
-
Save sabesansathananthan/a3db51e66cf44a12b8619eeba11e90ab to your computer and use it in GitHub Desktop.
How to override methods in localStorage?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
((win) => { | |
const nativeLocalStorage = win.localStorage; | |
win.nativeLocalStorage = nativeLocalStorage; // keep the original usage | |
class MyLocalStorage { | |
setItem(key, value) { | |
console.log('MyLocalStorage.setItem', key, value); | |
nativeLocalStorage.setItem(key, value); | |
} | |
getItem(key) { | |
console.log('MyLocalStorage.getItem', key); | |
return nativeLocalStorage.getItem(key); | |
} | |
} | |
const myLocalStorage = new MyLocalStorage(); | |
// Assign the newly created instance to localStorage | |
Object.defineProperty(win, 'localStorage', { | |
value: myLocalStorage, | |
writable: true, | |
}); | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment