blazor-webassemblysession-storagejava-interop

Blazor WebAssembly **Microsoft.JSInterop.JSException** Error: The value 'sessionStorage.length' is not a function


From a basic standpoint what I am trying to do is get a list of keys (key names) from session storage.

The way I am trying to do this is by calling the JsRuntime.InvokeAsync method to:

  1. Get the number of keys in session storage, and

  2. loop thought the number of items in session storage and get the key name.

     public async Task<List<string>> GetKeysAsync()
     {
         var dataToReturn = new List<string>();
    
    
         var storageLength = await JsRuntime.InvokeAsync<string>("sessionStorage.length");
    
         if (int.TryParse(storageLength, out var slength))
         {
    
             for (var i = 1; i <= slength; i++)
             {
                 dataToReturn.Add(await JsRuntime.InvokeAsync<string>($"sessionStorage.key({i})"));
             }
         }
    
         return dataToReturn;
     }
    

When calling the JsRuntime.InvokeAsync($"sessionStorage.length")) or JsRuntime.InvokeAsync($"sessionStorage.key(0)")) I am getting an error "The value 'sessionStorage.length' is not a function." or The value 'sessionStorage.key(0)' is not a function.

I am able to get a single items using the key name from session storage without issue like in the following example.

    public async Task<string> GetStringAsync(string key)
    {
        return await JsRuntime.InvokeAsync<string>("sessionStorage.getItem", key);
    }

When I use the .length or .key(0) in the Chrome console they work as expected, but not when using the JsRuntime.


Solution

  • I was able to get this to work without using the sessionStorage.length property. I am not 100% happy with the solution, but it does work as needed.

    Please see below code. The main thing on the .key was to use the count as a separate variable in the InvokeAsync method.

    I think the reason for this is the JsRuntime.InvokeAsync method adds the () automatically to the end of the request, so sessionStorage.length is becoming sessionStorage.length() thus will not work. sessionStorage.key(0) was becoming sessionStorage.key(0)(). etc. Just that is just a guess.

        public async Task<List<string>> GetKeysAsync()
        {
            var dataToReturn = new List<string>();
    
            var dataPoint = "1";
    
            while (!string.IsNullOrEmpty(dataPoint) )
            {
                dataPoint = await JsRuntime.InvokeAsync<string>($"sessionStorage.key", $"{dataToReturn.Count}");
    
                if (!string.IsNullOrEmpty(dataPoint))
                    dataToReturn.Add(dataPoint);
            }
    
            return dataToReturn;
        }