0

update The question is not answered yet. I have updated the question to provide more context.

Updated Update I switched the storage to chrome.storage.local, and the data appears to be stored there now, but I am still having trouble loading it back into the user variable. When the function runs it does not throw an error, but it shows that result is undefined.

I am very confused. I must be missing something but I don't know what that thing is. I am writing a smart home Chrome Extension and I want to persist data across the options (where the user logs in) and popup (devices) pages. There is sensitive information here, so I chose to use chrome.storage.session.

However, my console seems to indicate that writing to storage.session was successful (it gets to the then statement to console.log a message). However, when I check the application session storage, there is nothing there. I tried chrome.storage.local, same result. I tried chrome.storage.sync, same result.

I have searched for other people with this problem, but I didn't find anything that seemed relevant. I may have missed it. I tried copy and pasting from Googles own documentation and that didn't work either.

There is quite a bit of optimization and refactoring I need to do, but I've also done quite a bit already. I made a gist with more complete code.

console output on options

user data stored: 

devices: []
pref: {dark: true}
profile: {
    email: 'phy@sr.com', 
    first_name: 'PleasePlease', 
    id: 18616, 
    last_name: 'JustWorkTheFirstTime', 
    mobile_phone: '+15555555555', …}
session: {
    access_token: '...', 
    expires: 1680126140, 
    refresh_token: '...', 
    user_id: 181818}
units: (4) [{…}, {…}, {…}, {…}]

** Result on devices from extension errors **

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'pref')

manifest.json

{
  "manifest_version": 3,
  "name": "SmartHome extension",
  "description": "A smart device dashboard for Chrome",
  "version": "0.0.1",
  "action": {
    "default_popup": "./devices.html",
    "default_icon": "./images/logo.png"
  },
  "options_page": "./options.html",
  "options_ui": {
    "page": "./options.html",
    "open_in_tab": false
  },
  "permissions": [
    "storage"
  ],
  "host_permissions": ["https://api.smarthome.com/*"]
}

SmartHomeApi.js

...

public class SmartHomeApi 
    {async session(email, password){

        const body = JSON.stringify({ 
            'email': email, 
            'password': password 
        });

        this.#setupRequest('/api/v1/sessions','POST', body);

        this.#options.headers['Content-Length'] = this.#options.body.length;

        const result = await fetch(this.#url.base+this.#url.endpoint, this.#options)
            .then( async (response) => {
                await response.json()
                    .then( async (body) => {
                        user.session = await body.data;
                        this.#options.headers.Authorization = `Bearer ${body.data.access_token}`;
                    } );

                return response.status ;
            } );
        
        await this.#getProfile(); // This seems to work fine
        await this.getUnits(); this also seems to work fine
        await this.#storeUser();

        this.#reset();

        return result;
    }

...

    async #storeUser(){

        await chrome.storage.session.set({ 'user': user })  
            .then( () => {
                console.log('user data stored:', user);
// Judging by this output, user is properly formed.
            } );
    }

        async loadUser(){
    /** @todo write this */
        await chrome.storage.session.get(["user"]).then((result) => {
            result = result.user;
            user.pref = result.pref;
            user.session = result.session;
            user.profile = result.profile;
            user.units = result.units;
            user.devices = result.devices;
            alert('user is:', user)
        });
    }

}
  • Devtools doesn't show chrome.storage in Chrome, it shows window.sessionStorage, which is a different thing. You'll have to run `await chrome.storage.session.get()` in console. – wOxxOm Mar 29 '23 at 22:02
  • @wOxxOm I see, thank you for that clarification! Yes, that is exactly what I expected. So in the gist I have a loadUser() method. However, that doesn't seem to load the information. I will update the post with those results. – The Jaded George Mar 29 '23 at 22:15
  • @wOxxOm Ah you are right, I have the async for loadUser(), but not the await. – The Jaded George Mar 29 '23 at 22:33
  • Update: Nope, still automatically redirects to the options page after it looks for data in chrome.storage.session and returns undefined. – The Jaded George Mar 29 '23 at 22:39
  • Apparently loadUser is called by something before storeUser. Set a breakpoint inside and inspect the callstack or use console.trace() – wOxxOm Mar 29 '23 at 22:51
  • I think I have it working, but somehow I introduced another bug causing errors in options.js which was working perfectly before. I couldn't get vscode to debug the extension, I will have to learn about that soon. update: ah, it was my loadUser(), running that method reset the values to undefined. It isn't even getting the data from chrome.storage.local within the same session() method. – The Jaded George Mar 30 '23 at 01:36
  • Okay, it is working on the same page. Thank you so much for your help @wOxxOm. I am hoping this works. – The Jaded George Mar 30 '23 at 01:53
  • Update: chrome.storage.session still isn't working, but chrome.storage.local is. This isn't a good place to store sensitive information, is it? – The Jaded George Mar 31 '23 at 19:22
  • If `local` works, but `session` doesn't, it means that the object is bigger than 1 MB or it has data that's not serializable e.g. a function, class, or Symbol inside. – wOxxOm Mar 31 '23 at 20:30

0 Answers0