Search code examples
javascriptblazor.net-6.0

Is it possible to alter the value of a parameter within a Blazor component using javascript?


I'm trying to add a component of a loading animation that runs while one of my components that contains an Iframe is still rendering. I want the loading animation to be able to recognise when the Iframe has been loaded so that it would stop and the Iframe/component would open fully rendered. Is there any way I could add a Boolean Parameter to my component and then alter it with the onload event on the Iframe event using JS?

Currently I have this, which does nothing else but initialize the loading screen component for 3 seconds before the iframe component. (The Initialized Parameter is the one I wish to alter using JS.)

enter image description here

enter image description here

I apologise in advance if I did not provide enough information, I'm still very new to SO and programming in general. Please feel free to ask me or correct me if anything in my explanation is unclear or wrong.


Solution

  • You can call a javascript function from Blazor and give a parameter for the javascript function to be able to answer back to Blazor. This way, you could call an init javascript function from blazor that will give you the possibility to call a Blazor function in return when it is necessary and then set the boolean to true.

    I did not try this code.

    In Blazor:

    @implements IDisposable
    @inject IJSRuntime JSRuntime
    
    @code{
    
      private DotNetObjectReference<NameOfYourRazorPage>? DotNetObjectRef;
      
      public bool isLoaded { get; set; } = false;
    
      protected override async Task OnAfterRenderAsync(bool firstRender)
      {
        if (firstRender)
        {
          await InitJavascript();
        }
      }
    
    
      public async Task InitJavascript()
      {
        DotNetObjectRef = DotNetObjectReference.Create(this);
        await JSRuntime.InvokeVoidAsync("initFunc", DotNetObjectRef);
      }
      
      [JSInvokable]
      public void IframeInitDone()
      {
        isLoaded = true;
        StateHasChanged();
      }
    
      public void Dispose()
      {
        DotNetObjectRef?.Dispose();
      }
    }
    

    In Javascript:

    window.initFunc = (dotNetHelper) => { 
      document.querySelector("iframe").addEventListener("load", iframeLoaded);
    
    
      function iframeLoaded(){
        dotNetHelper.invokeMethodAsync('IframeInitDone');
      }
    
    };
    

    I don't know what happens if the iframe has finished loading before the function is called.

    Here is the Doc;