I hate JavaScript or How to inject JavaScript into Blazor?

First I would like to confess that I do not hate JavaScript, I simply do not know it well enough… More importantly I lack hands-on experience with it.

Once I heard about Blazor I was very excited.

With Blazor you do not need to write JavaScript code at all, you write C# and all needed js is being scaffolded for you.
That is such a blessing for back end developers or wannabe developers (who do not know JavaScript) like me.

But the world is a messy place or if I want to use more scientific/correct term – heterogeneous. A single piece of technology or technology stack rarely exists by itself, as it needs to integrate, communicate and interact with the rest (of the mess) of the world.

And if you think about it,  even a simple single page application website can benefit from different integrations achieved by <script> tag in the <head> of the page. Some of the most common integrations are web page style, usage analytics and last but not least advertising.

I know what you are thinking right now, no JavaScript no ads but it is not as simple as it may appear. Ads are a revenue stream for bloggers. It is not their primary revenue generator but it can help to offset at least hosting costs.

I was able to find a couple of ways on how to inject JavaScript into Blazor:

  1. Adding support for Google AdSense To your Blazor WebAssembly Apps
    1. Using custom Ads Component
    2. Conclusion: Looks Complex and cumbersome. Not able to find source code to understand it better.
  2. Dynamically Add JavaScript in Blazor Components (geekinsta.com)
    1. Using custom script loader component
    2. Conclusion: Looks Complex. Maybe I am just not able to wrap my head around it.
  3. CloudFlare Workers – Add JavaScript at the edge
    1. Inject Javascript at the Edge
    2. Conclusion: Modular and separate from website code. But depends on Cloudflare.

CloudFlare Workers

Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure. Sounds cool, right!

To get more understanding and knowledge about CloudFlare Workers and typical use case, please refer to their awesome documentation.

For our simple purposes we will be utilizing the HTMLRewriter class.

Easiest way to jump start a project would be to use one of the templates.

Pseudo code

Fetch request
Append script into head element
return new request

Full code

In the code below I added Google Analytics script into my Blazor Web Application. This code is live and is used for my IsBehindCDN service. You can use IsBehindCDN to check if Domain is fronted by Content Delivery Network provider.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Fetch and log a given request object
 * @param {Request} request
 */
async function handleRequest(request) {
  
  const oldResponse = await fetch(request)
  
  let newResponse = new HTMLRewriter()
    .on("head", new insertHeadScript())
    .transform(oldResponse)

  return newResponse

}

class insertHeadScript{
  element(element) {  
    element.append(`<script async src="https://www.googletagmanager.com/gtag/js?id=<ID>"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'ID');
    </script>`, {html: true});
  }
}

Summary

With free CLoudFlare account, free CloudFlare Workers and few lines of code separated from your main project and source code you can inject JavaScript into Blazor, actually you can inject it into any web app.

Hope that helps.

Thanks a lot for reading.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.