Programmatically inject custom script into page body at runtime - like Browser Link

350 Views Asked by At

I'm looking for a way to inject a custom script into the _Layout.cshtml purely from code. _Layout.cshtml cannot know anything about it. Just like Browser Link does it.

You simple write this:

app.UseBrowserLink();

And this gets injected into the body at runtime.

    <!-- Visual Studio Browser Link -->
    <script type="application/json" id="__browserLink_initializationData">
        {"requestId":"a717d5a07c1741949a7cefd6fa2bad08","requestMappingFromServer":false}
    </script>
    <script type="text/javascript" src="http://localhost:54139/b6e36e429d034f578ebccd6a79bf19bf/browserLink" async="async"></script>
    <!-- End Browser Link -->
</body>

There is no sign of it in _Layout.cshtml. Unfortunately Browser Link isn't open source so I can't see how they have implemented it. Browser Link source now available

So I was wondering how it was done?

2

There are 2 best solutions below

2
Terrance00 On

Razor allows you to do this quite easily - you can even use a flag.

Example:

In your controller:

ViewData["RegisterCustomCode"] = "true";

In your View (.cshtml):

@if (ViewData["RegisterCustomCode"] == "true")
{
    <text>
        <script src="..."></script>
    </text>
}
2
Métoule On

It's not open source, but you can easily decompile it to see how it works. From a comment in the source code:

This stream implementation is a passthrough filter. It's job is to add links to the Browser Link connection scripts at the end of HTML content. It does this using a connection to the host, where the actual filtering work is done. If anything goes wrong with the host connection, or if the content being written is not actually HTML, then the filter goes into passthrough mode and returns all content to the output stream unchanged.

The entire thing seems pretty involved, but doesn't seem to use anything not available out of the box, so I guess it can be possible to code a similar thing.