Hardipsinh Jadeja
Hardipsinh Jadeja

Reputation: 1297

How to get chrome storage values via local getter setter class?

I have created a local class in a JavaScript file with following content:

class CustomChromeStorage {
    //#region userName
    get userName() {

        let isCurrentValueSet = false;
        chrome.storage.sync.get('userName', function (obj) {
            this._userName = obj;
            isCurrentValueSet = true;
        });
        while (true) {
            if (isCurrentValueSet) {
                return this._userName;
            }
        }
    }

    set userName(newValue) {
        this._userName = newValue;
        chrome.storage.sync.set({ 'userName': newValue }, function () {
        });
    }
    remove_userName() {
        this._userName = null;
        chrome.storage.sync.remove('userName', function () {
        });
    }
    //#endregion userName

My Idea to do such type of code is when I write somewhere else in my code like:

alert(new CustomChromeStorage().userName);

Then my code simply fetches username from chrome storage and show it via an alert. In order to fetch a value from chrome storage we need to provide a callback with as parameter the value. I know this is good practice for asynchronous process but it sometimes becomes cumbersome for me to handle all the callbacks.

I want that when I fetch value from chrome storage via my custom class to execute current code asyncronously. This is why I have written infinite while loop inside getter method of that property but the problem is when I try to alert username via custom chrome storage class my total program execution becomes hang.

The reason behind it is that I initially set isCurrentValueSet = false which never gets true inside while loop.

If anybody have any idea why it does not set to true inside while loop then please let me know.

Upvotes: 0

Views: 353

Answers (1)

Troy Wray
Troy Wray

Reputation: 1018

The obj returned from sync.get is {userName: value} - use obj.userName.

The reason isCurrentValueSet doesn't get set to true is because the function is asynchronous - when the callback executes, it doesn't have access to the class variable isCurrentValueSet.

What you're trying to achieve is just wrong. It's a fact that storage requests are asynchronous for the good of the user and browser performance. You have to learn to design around it and it's easy enough when you get used to it.

You can retrieve multiple variables in one hit so if you have a section of code that needs several variables, just do:

chrome.storage.sync.get({a:"",b:"",c:0,d:[]}, function(result) {
  a = result.a
  b = result.b
  c = result.c
  d = result.d
  your code
});

By passing an object in, you can request multiple variables and define defaults for if they don't yet exist in storage. Of course you don't have to extract the variables.

Upvotes: 3

Related Questions