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