2

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?

Snæbjørn
  • 10,322
  • 14
  • 65
  • 124

2 Answers2

2

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.

Métoule
  • 13,062
  • 2
  • 56
  • 84
0

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>
}
Terrance00
  • 1,658
  • 1
  • 20
  • 29
  • But that implies that the view knows about it, and that's a deal breaker – Snæbjørn Aug 04 '17 at 08:32
  • Well, guess I misunderstood the scope of the question. I'm not quite sure if browser link 'like' code injection is possible with core. But it is an interesting question. Will +1 – Terrance00 Aug 04 '17 at 08:45