Injecting metrics code into Blazor app index.html when code is templated

359 Views Asked by At

I am trying to add various types of metrics into a Blazor web assembly application. The majority of analytics, such as GA, Insights, Clarity all utilise a JavaScript loaded on the main page of the site, or a header component.

Now adding the metrics script directly into the index.html would be an option, however the codebase is basically templated to new clients as docker images. Therefore it is not possible to just add the metrics JavaScript into the index.html as it would be the same for all client applications that are generated from the codebase.

I am fairly new to Blazor but in MVC, I would just read the metrics client ID out of a azure config setting supplied to the docker image and then inject this via razor into the layout page, as appropriate.

It does not seem possible to do this in Blazor and it would also seem that you cannot add this kind of razor markup into index.html so how would I get around this issue?

I have seen a topic here that suggests it is possible to inject JavaScript into the index.html, but what about injecting a variable onto the page?

1

There are 1 best solutions below

0
On BEST ANSWER

After trying a number of different methods it would appear that it is simply not possible to insert dynamic javascript into the index.html of a blazor application. The closest result I had, was by using MarkupString to insert the script into the header (an idea found here) and whilst this did appear in the DOM, it did not appear in the page source and therefore did not work.

So if I cannot add dynamic script into the index.html then how about replacing the index.html entirely for each application that loads?

I did this by setting an azure config string to the name of a html file for each client, all of which were copies of the original index.html just with their respective telemetry scripts within them and then in the server program.cs manipulated the default method used to map the fall back file.

app.MapFallbackToFile(myAppSetting);

This now means that when a pod is loaded for each client from the same docker image/codebase the settings can be passed in via helm to the docker image for the config and then the app can pickup the correct index.html for that client.