Search code examples
javascriptasp.net-coreblazor.net-8.0

Embed javascript in the Blazor component in .NET 8


I'm migrating my ASP.NET Core website to .NET Blazor Web App with static render. I've encountered problems with embeding external js script into blazor component.

The scenario is I have one blazor page where I want to show some gists:

<script src="https://gist.github.com/robocik/9506834.js"></script>

By default, when I open this website, these scripts are not invoked. I found a partial solution described here: https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/static-server-rendering?view=aspnetcore-8.0

This solution works with scripts which are hosted locally. But in this case, gist script is hosted externally therefore I get exception:

Access to script at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I embed external script in my blazor component in .NET 8?


Solution

  • I've found that the problem with embeding javascript was because of the enhanced navigation - a new feature in .NET 8 Blazor. So to fix my issue, I have disabled enhanced navigation by adding

    data-enhance-nav="false"

    to any link pointing to my page with javascript, like this:

    <a href="/Faq" title="FAQ" class="nav-link" data-enhance-nav="false">FAQ</a>. Now when a user click this link to go to the FAQ page, all javascripts on this FAQ page will be invoked.