Blazor NET8 localStorage getItem gives IJSRuntime error or disconnects from server

I am updating a Blazor hosted web app from net6 to a Blazor Web App in net8, and have been unable to retrieve an item from local storage. I can successfully SET the item in localStorage, and after I set it, I want to retrieve it. But on GET item I get the IJSInProcessRuntime not available error (in other variations of my code I become disconnected from the server). A similar stackoverflow question included this response: ” you can just use the OnAfterRender hook and use StateHasChanged ” , which I thought I was doing: since the IJS runtime is not available until after the page has rendered, my GetItem is now in the OnAfterRenderAsync method, and I am using StateHasChanged once I have set my GetImageBool trigger to true to get the item. I have tried different rendermodes, with and without prerendering, and get the same error. Per the Microsoft docs, I’ve moved my “SET” javascript (which works) to MyAssemblyName.lib.module.js. I tried a workaround to have eventArgsCreator also return the item instead of only saving it in localstorage, however, an async method is required to to create the saved value (“thisimage” is a Base64string), and the app crashes on load when I set eventArgsCreator to be an async function (to await the call to funcLocal). Program.cs correctly contains builder.Services.AddBlazoredLocalStorage(); What am I missing?

Set the value in localStorage: MyAssemblyName.lib.module.js:

    blazor.registerCustomEventType('pastemultimedia', {
        browserEventName: 'paste',
        createEventArgs: eventArgsCreator
    });   
}

 function eventArgsCreator(event) {
    console.log("In processPasteEvent");
    const items = event.clipboardData.items;
    const acceptedMediaTypes = ["image/png"];
    let isMultimedia = false;
    let data = null;
    let file = null;

    for (let i = 0; i < items.length; i++) {
        file = items[i].getAsFile();
        if (!file) continue;
        if (!items[i].type.includes('image')) continue;
        if (acceptedMediaTypes.indexOf(items[i].type) === -1) continue;
        isMultimedia = true;
        data = URL.createObjectURL(file);
        funcLocal(file);
        break;
    }
    
    return {
        IsMultimedia: true,
        Data: data
    };
}

async function funcLocal(fileParam) {
    const result = await blobToBase64(fileParam);
    console.log(`Saving to local storage: ${result.substring(0, 100)}`); // Display first 100 chars for brevity
    localStorage.setItem("thisimage", result);
    return result;
}

Blazor page:

@page "/stackoverflow"

@inject IJSRuntime JS
@inject Blazored.LocalStorage.ISyncLocalStorageService localStorage

@rendermode @(new InteractiveServerRenderMode(prerender: false))

@if (GetImageBool && !string.IsNullOrEmpty(Image))
{
    @Image

    <img src="@Image" />
}

<input id="textarea"
               Title="Right-click to Paste Image from Snipping Tool"
               @onpastemultimedia="HandlePasteMultimedia"
               class="pasteimagearea"
               style=@($"visibility:{(SavingImage ? "hidden" : "visible")}") />

<style>
    .pasteimagearea {
        background: url(images/PASTEIMAGE.png) center center no-repeat;
        width: 50vw;
        height: 50vh;
    }
</style>

        
@code {
 
    public bool SavingImage { get; set; } = false;
    public string Image { get; set; } = "";
    private bool GetImageBool { get; set; } = false;
 
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (GetImageBool)
        {
// THIS IS LINE 48 WHICH TRIGGERS THE ERROR:
            var thisvar = localStorage.GetItemAsString("thisimage");  
            Image = thisvar;
        }
    }

    public async Task HandlePasteMultimedia(PasteMultimediaEventArgs e)
    {             
            SavingImage = true;
            GetImageBool = true;
            StateHasChanged();         
    }

   
}

Custom Event / Argument definition:

 public class PasteMultimediaEventArgs : EventArgs
 {
     public bool IsMultimedia { get; set; }
     public string? Data { get; set; }
 }

 [EventHandler("onpastemultimedia", typeof(PasteMultimediaEventArgs),
 enableStopPropagation: true, enablePreventDefault: true)]
 public static class EventHandlers { }

Complete error message:

[2024-07-15T14:00:19.626Z] Error: System.AggregateException: One or more errors occurred. (IJSInProcessRuntime not available)
 ---> System.InvalidOperationException: IJSInProcessRuntime not available
   at Blazored.LocalStorage.BrowserStorageProvider.CheckForInProcessRuntime()
   at Blazored.LocalStorage.BrowserStorageProvider.GetItem(String key)
   at Blazored.LocalStorage.LocalStorageService.GetItemAsString(String key)
   at MyAssemblyName.Client.Pages.StackOverflowComponent.OnAfterRenderAsync(Boolean firstRender) in C:MyAssemblyNameMyAssemblyName.ClientPagesStackOverflowComponent.razor:line 48

4

Thanks to Brian Parker for pointing me in the right direction!

The IJSInProcessRuntime error message was due to my using the synchronous library from Blazored, not the async library as required in their docs. Just changing that worked for extremely small image files. For my real-world image sizes (just thumbnails), I would get the server disconnect error.

To address the server disconnect, I found the answer in ASP.NET Core Blazor SignalR guidance . First I added this to my logging as recommended in the console error message:

appsettings.json

"Microsoft.AspNetCore.SignalR": "Debug"

which resulted in a more meaningful error message showing the message had exceeded the size limit. I increased the message size limit from the default of 32K to 528K :

Program.cs

   builder.Services.AddRazorComponents()
       .AddInteractiveServerComponents()
        .AddHubOptions(options => options.MaximumReceiveMessageSize = 528 * 1024)
       .AddInteractiveWebAssemblyComponents();

I also modifed the code in OnAfterRenderAsync to wait in case “thisimage” were not immediately available. See revised Blazor page below.

And on a side note (is this a hack?), I found that if my “textarea” element were condtionally rendered (e.g. inside an @if block) then the custom event listener would not be able to find it, so I used conditional css styling visibility: visible / visibility:hidden instead to control its appearance.

Revised Blazor Page:

@page "/stackoverflow"

@inject IJSRuntime JS
@inject Blazored.LocalStorage.ILocalStorageService BlazoredLocalStorage

@if (GetImageBool && !string.IsNullOrEmpty(Image))
{
   @Image
 

    <img src="@Image" />
}

<input id="textarea"
               Title="Right-click to Paste Image from Snipping Tool"
               @onpastemultimedia="HandlePasteMultimedia"
               class="pasteimagearea"
               style=@($"visibility:{(SavingImage ? "hidden" : "visible")}") />

<style>
    .pasteimagearea {
      
        background: url(images/PASTEIMAGE.png) center center no-repeat;
        width: 50vw;
        height: 50vh;
  
    }
</style>

        
@code {

    public bool SavingImage { get; set; } = false;
    public string? Image { get; set; }
    private bool GetImageBool { get; set; } = false;

    private int maxtimetowait { get; set; } = 5000;
    private int timewaited { get; set; } = 0;
    private int timeinterval { get; set; } = 500;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (GetImageBool)
        {
            while (string.IsNullOrEmpty(Image) && (timewaited < maxtimetowait))
            {
                var thisvar = await JS.InvokeAsync<string>("localStorage.getItem", "thisimage");
                // this also works using the injected Async libary :
                var BlazoredVar = await BlazoredLocalStorage.GetItemAsync<string>("thisimage");

                Image = thisvar;
                if (!string.IsNullOrEmpty(Image)) break;
                await Task.Delay(timeinterval);
                timewaited += timeinterval;
            }
            NextStep();
        }
    }

    public void HandlePasteMultimedia(PasteMultimediaEventArgs e)
    {
        SavingImage = true;
        Image = "";
        GetImageBool = true;
        StateHasChanged();
    }

    public void NextStep()
    {
        StateHasChanged();
        GetImageBool = false;
        Console.WriteLine("I am in NextStep");
    }

}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật