0

I am new to Blazor Webassembly and find out how to call a javascript function from .NET code. My question is: Is it possible to read and write also a javascript variable from .NET. Here an example:

Javascript code loaded into page:

var Namespace1 = {
    prop1: 42, 
    func1: function () {
        return 42;
    }
}

from .NET I can call the function Namespace1.func1:

@code { 
    //private int prop1 { get; set; } = 1;
    private int ret1 { get; set; }

    override protected async Task OnInitializedAsync() {
        // Error: The value 'window.Namespace1.prop1' is not a function.
        // ret1 = await JSRuntime.InvokeAsync<int>("Namespace1.prop1"); 
        ret1 = await JSRuntime.InvokeAsync<int>("Namespace1.func1");
        // return base.OnInitializedAsync();
    }
}

Is it possible to access also Namespace1.prop1 from .NET

1 Answer 1

5

That's not possible currently as IJsRuntime only exposes methods that invoke javascript functions. Details here on Microsoft docs

But you can write a js function and return a property:

var Namespace1 = {
    prop1: 42, 
    func1: function () {
        return prop1;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the information. Because it is for a project with a js lib (not my code) with a lot of properties it will not work. I will use angular for this.
You can create your own javascript that can have functions that can access the js properties that you want to access. So basically blazor > your js > readonly js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.