iframeblazorblazor-webassemblypostmessagelegacy

Postmessage to parent window from Blazor WASM hosted in an iFrame


I'm just about to embark on a new role in my company. We've got some legacy web apps (asp and aspx) and we want to start developing new Blazor modules for these apps, without completely re-writing them. One idea I had was hosting the Blazor wasm inside an iFrame. I then wondered how the blazor module could communicate with the old legacy apps and found an article on a suggested route to do this using the javascript postMessage api

Add client side Blazor to existing ASP.NET MVC5 app

So I've got a trivial Blazor wasm app with a button on it. The click event just calls a javascript function

    private async Task OnClick()
    {
        Console.WriteLine("Write to the console in C#! 'OnClick' button selected.");
        await JS.InvokeVoidAsync("interopFunctions.callParent");
    }

And I've a .js file in wwwroot that has the following

    var interopFunctions = {};

    interopFunctions.callParent = () => {
        debugger;
        window.postMessage('test', "*");
    };

This all works when running it locally as a Blazor app, but when I try and drop it in an iFrame in a separate asp.net mvc core project, although the blazor shows up ok, I get an error when I press the test button

    <iframe width="560" height="315" src="https://localhost:7295/" frameborder="0" allowfullscreen</iframe>
    crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
          Unhandled exception rendering component: Could not find 'interopFunctions.callParent'     ('interopFunctions' was undefined).

I'm certainly no Blazor expert and am just starting out with the framework, but wonder if this is a sensible thing to be doing, why it might not work and if it can never work what sort of alternatives are there for Blazor in old legacy apps.

thanks

[Update] This all seems to work fine in a static web page, just not from an asp.net mvc core app.


Solution

  • Very strange. Checked again this morning and the asp.net mvc code is now working. I was a bit confused by the static page working (see update comment) so came back to it today find things working. I must have done something wrong. Going to try closing the question now.