computer-with-lock

Previously in .Net 5 when the browser lost connection to the server, we were able to reload the page (to re-establish the Signal-R connection) using:

<script>
    Blazor.defaultReconnectionHandler._reconnectCallback = function (d) {
        document.location.reload();
    }
</script>

Whilst this is an undocumented solution it worked.

In .Net 6 though, the TypeScript that builds Blazor has been changed. The above script no longer works. (See here: Configurable Reconnection Behaviour.) The error is caught in the console: Uncaught TypeError: Cannot set properties of undefined (setting '_reconnectCallback')
There have been solutions thrown about (see above issue) using the _reconnectionDisplay, but I was never able to get any of those to work.

It turns out though, that the _reconnectCallback hasn’t been deprecated, rather it just seems to be delayed in defining. To solve this all that is needed to do is manually start Blazor and then setup the _reconnectCallback. Just add autostart="false" to the Blazor script, and then call Blazor.start().then(() => {...}); and you can add any JavaScript you like.
The final JS should look like this:

<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
    Blazor.start().then(() => {
        Blazor.defaultReconnectionHandler._reconnectCallback = function (d) {
            document.location.reload();
        }
    });
</script>

With this the page will still show the default _reconnectionDisplay when it loses connection, but will also try and reload the page to re-establish the Signal-R connection to the server.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

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