How to use IJSRuntime from class library

1.3k views Asked by At

Let's say someone wants to write a NuGet package that writes cookies in Blazor via JS interop.

IJSRuntime.InvokeAsync calls a method, and that method has to be defined someone -- outside of the scope of the DLL.

Is there a way to inject the required script function so that the library can invoke it without requiring awareness of the front-end?

I need to call something like this. Which isn't a function.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC"

I looked at the implementation of Blazored LocalStorage, and localstorage is set and read using standard methods so that's a lot easier.

1

There are 1 answers

0
Etienne Charland On BEST ANSWER

Well... there is "eval" function!

This works.

await jsRuntime.InvokeVoidAsync("eval", "document.cookie = ''");

But then, have to be careful about escaping parameters.

It's not a very scalable strategy for complex libraries though. 3rd party libraries instead require you to add a reference to their .js file.