0

I have the following JavaScript code in a .js file:

export function testAlert() {
  alert('Testing Blazor');
}

When I added this to my Razor component, I get a warning:

enter image description here

I added the following to the index.html file - as recommended:

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>BlazorTest</title>
  <base href="/" />
  <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
  <link href="css/app.css" rel="stylesheet" />
  <link href="BlazorTest.styles.css" rel="stylesheet" />
  <script type="text/javascript" src="scripts/testing.js"></script>
</head>

Modified the component accordingly:

@inject IJSRuntime JS

protected override async Task OnAfterRenderAsync(bool firstRender)
{
  base.OnAfterRenderAsync(firstRender);
  await JS.InvokeAsync<string>("testAlert");
}

When I load the page, I get the following error:

Unhandled exception rendering component: Could not find 'testAlert' ('testAlert' was undefined).

I checked the source of the page, and it looked like this:

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>BlazorTest</title>
  <base href="/" />
  <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
  <link href="css/app.css" rel="stylesheet" />
  <link href="BlazorTest.styles.css" rel="stylesheet" />
</head>

What happened to the modified index.html with the loaded script?

Nestor
  • 8,194
  • 7
  • 77
  • 156
  • Sometimes the index.html file is cached by the browser. That may be the case here. Have you tried reloading the page after clearing the cache? Ctrl-F5 usually does it for me. – Eric King Mar 08 '21 at 20:07
  • 2
    I think if you remove the export from the function, and make sure you have saved the changes to index.html your code should work. – David Masterson Mar 08 '21 at 20:07
  • Using "export" from JS or TS "compiles" to some funky code that even re-instantiates objects. I personally dislike it very much. Anyway, perhaps removing "export" will fix this, otherwise - see what you actually get in the browser devtools, maybe there is a layer of objects that you actually get and you may need to match those namespaces in the JS Interop call – rdmptn Mar 10 '21 at 20:29
  • 1
    @EricKing Yes, it looks like it was heavily cached: I added some HTML code and the change was invisible until I hit Ctrl+F5. Strangely the next edit didn't require it, and immediately refreshed. Promote your comment to an answer, I'll accept is. – Nestor Mar 11 '21 at 17:55

1 Answers1

1

Sometimes the index.html file is cached by the browser. That may be the case here.

Usually forcing a refresh with Ctrl-F5 will force a download of the newly edited file.

Eric King
  • 11,594
  • 5
  • 43
  • 53