Skip to content Skip to sidebar Skip to footer

Could Not Find Property Of Window When Doing Js Interop With Blazor

Hello i am trying to call a method from a js file from Blazor. My file structure is like this: -root -JSInterop.cs -js(folder) -meth.js (file containing the js method) I

Solution 1:

JSRuntime.Current.InvokeAsync takes a js function identifier relative to the global window scope as its first argument. So in your js file you may have :

window.methods = {
    print: function (message) {
    return"from js" + message
}

Add your js file in index.html

<scriptsrc="css/bootstrap/bootstrap-native.min.js"></script><scriptsrc="_framework/blazor.webassembly.js"></script><scriptsrc="js/meth.js"></script>

and call it from .Net as follows

await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");

Solution 2:

// Try this:// Don't call your class JSInteroppublicclassMyJSInterop {
        publicstaticasync Task<string> ChangeText() {
            try {
                var data = await JSRuntime.Current.InvokeAsync<string>("methods.print","mymessage");
                Console.WriteLine($"ReturnedFromJS:{data}");
                return data;
            } catch (Exception ex) {

                return ex.Message;
            }

        }
    }

// Js file
window.methods = {
    print: function (message) {
        return"from js" + message;
    }
};

Solution 3:

Below is an end to end example of writing cookie.

step 1 - Add MatButton and sets it onClick attribute to delegate.

<MatButtonTrailingIcon="favorite" @onclick="@(async () => await AddItemtoShoppingCart(@item))"Label="add"></MatButton>

Step 2

@code{
publicasync Task AddItemtoShoppingCart(FoodItem selectedItem)
    {
        var test = await JSRuntime.InvokeAsync<object>("blazorExtensions.WriteCookie", "cookieName", "cookieValue", "cookieExpiryDate");
       
    }

}

Step 3 - Add below javasceipt in_Host.cshtml

<script>window.blazorExtensions = {

            WriteCookie: function (name, value, days) {

                var expires;
                if (days) {
                    var date = newDate();
                    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                    expires = "; expires=" + date.toGMTString();
                }
                else {
                    expires = "";
                }
                document.cookie = name + "=" + value + expires + "; path=/";
            }
        }
    </script>

Post a Comment for "Could Not Find Property Of Window When Doing Js Interop With Blazor"