Estoy tratando de cargar una función de javascript en un componente de razor pero recibo un error.
@inject IJSRuntime JsRuntime @if (listProducts != null) { <table class="table"> <thead> <tr> <th>Name</th> <th>Home place</th> <th>Expiration</th> <th>Phone number</th> <th>Tea</th> <th>Local</th> <th>App</th> <th>Company /Lease</th> <th>Road time</th> <th>Notes</th> <th></th> </tr> </thead> <tbody> @foreach(var product in this.listProducts) { <ProductItemComponent Product="product" OnProductDeleted="OnProductDeleted"></ProductItemComponent> } </tbody> </table> } @code { protected override async Task OnInitializedAsync() { await LoadProducts(); await JsRuntime.InvokeVoidAsync("exampleJsFunctions.DisableCopy"); } } Al principio estoy inyectando IJSRuntime como @inject IJSRuntime JsRuntime y en OnInitializedAsync() estoy llamando a mi función que está en _Layout.cshtml que se parece a esto
<script> window.exampleJsFunctions = { DisableCopy: function (data) { if (document.layers) { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = clickNS4; } else if (document.all && !document.getElementById) { document.onmousedown = clickIE4; } }} </script>¿Alguna idea sobre lo que está mal?
Aquí hay una demostración sobre cómo llamar a js en blazor:
wwwroot/js/test.js (ponga el código js en el archivo js de wwwroot):
window.exampleJsFunctions = { DisableCopy: function (data) { if (document.layers) { document.captureEvents(Event.MOUSEDOWN); document.onmousedown = clickNS4; } else if (document.all && !document.getElementById) { document.onmousedown = clickIE4; } }}Pages/_Host.cshtml (añadir referencia de test.js en _Host.cshtml):
... <html lang="en"> <head> ... </head> <body> ... <script src="~/js/test.js"></script> </body> </html> No llame a js en OnInitializedAsync() . El componente se representa de forma estática. Por lo tanto, las llamadas de interoperabilidad de JavaScript no se pueden emitir en este momento. Por lo tanto, puede llamarlo en OnAfterRender .
componente de la maquinilla de afeitar:
@inject IJSRuntime JsRuntime @code { protected override void OnAfterRender(bool firstRender) { JsRuntime.InvokeVoidAsync("exampleJsFunctions.DisableCopy"); } }