1

I've a .js file which contains following javascript code:

         <script>     
            abc= window.abc|| {};
            abc.Metrics = abc.Metrics || {};
            abc.Metrics.sc = abc.Metrics.sc || {};
            abc.Metrics.sc.country = "us";         /***dynamic value based on site***/
            abc.Metrics.sc.language = "en";        /***dynamic value based on site***/
            abc.Metrics.sc.segment = "corp";      /***dynamic value based on site***/
            abc.Metrics.sc.customerset = "19";    /***dynamic value based on site***/
            abc.Metrics.sc.cms = "stp";           /***dynamic value based on site***/
            abc.Metrics.sc.pagename = "pname";  /***relevant unique page name***/
            abc.Metrics.sc.applicationname = "Browse:Product Detail"; 
         
        </script>
      
      <!-- Refer the below script in DEV -->
      <script src="//gbxDev/Bootstrap.js"></script>

Now, I want to inject this piece of code from .cs file without adding the reference of this js file in _Host.cshtml. Also, I've to set those variable values dynamically at the startup. Is it possible in blazor server side?

2
  • Do you want to add this configuration script to all pages or just some pages? Commented Sep 2, 2021 at 11:39
  • I want this configuration script on all pages but want to inject it dynamically with dynamic values to the variables. Commented Sep 2, 2021 at 12:17

1 Answer 1

7

You can add any js file dynamically with this way:

@code {   
 protected override async void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync(identifier: "import", "/js/yourfile.js");
        }
    }
}

The above code just lets you call. If you want to call with initial value you want to send. You should follow this way:

@code {   
 protected override async void OnAfterRender(bool firstRender)
    {
        String parameter1 = "test";
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync(identifier: "yourMethodName", parameter1);
        }
    }
}

JS File Side

window.yourMethodName= (parameter) => { *** }

*You have to add this js file in _host.cshtml

Sign up to request clarification or add additional context in comments.

1 Comment

It should be "await jsRuntime" not "await JSRuntime" otherwise you will get a non-existing method error when trying to call InvoiceVoidAsync

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.