Adding JavaScript and Services to Write to LocalStorage
Explore how to build a local storage service in Blazor WebAssembly by writing JavaScript functions and creating C# interfaces and classes. Understand how to invoke JavaScript from Blazor to save data to the browser's localStorage, enabling persistent client-side storage.
Writing JavaScript to access localStorage
We need to write the JavaScript functions that will read to and write from the browser’s localStorage. We do this as follows:
- Right-click the
wwwrootfolder and select the “Add, New Folder” option from the menu. - Name the new folder
scripts. - Right-click the
scriptsfolder and select the “Add, New Item” option from the menu. - Enter “javascript” in the “Search” box.
- Select “JavaScript File.”
- Name the file
bweInterop.js. - Click the “Add” button.
- Enter the following JavaScript:
- Open the
wwwroot\index.htmlfile. - Add the following reference within the
bodyelement:
- Make sure to add it before the reference to
_framework/blazor. webassembly.js.