Reputation: 81
I am building a Blazor app, I need to dynamically add a JavaScript file that is used only in a single Blazor component. As you would be aware Blazor allows adding script tags only to the root HTML document. This makes it difficult to add JavaScript files that are required only in a single component.
The script is
It is important to set the data-main="payment-js" attribute on the script tag.
Are there any restrictions around iframe rendering in Blazor? The script renders multiple iframes on the specific Blazor components as part a PCI compliant payment system integration.
The script works in a simple HTML file.
I would be grateful for any assistance
Upvotes: 7
Views: 6946
Reputation: 21
try JavaScript isolation in JavaScript modules:
download payment.1.3.min.js to your wwwroot, and try this codes
public partial class Demos : IAsyncDisposable
{
[Inject] IJSRuntime? JS { get; set; }
private IJSObjectReference? module;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
try
{
if (firstRender)
{
module = await JS!.InvokeAsync<IJSObjectReference>("import", "./payment.1.3.min.js" + "?v=" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
Instance = DotNetObjectReference.Create(this);
}
}
catch (Exception e)
{
if (OnError != null) await OnError.Invoke(e.Message);
}
}
public virtual async Task DoSomePayment(string fileName, string fileURL)
{
await module!.InvokeVoidAsync("payment1234", fileName, fileURL);
}
async ValueTask IAsyncDisposable.DisposeAsync()
{
if (module is not null)
{
await module.DisposeAsync();
}
}
}
Upvotes: 2
Reputation: 405
This can be achieved by using a script loader
and JSRuntime
. Check this out.
Upvotes: 1
Reputation: 11332
Edit:
Maybe MarkupString
could help:
@((MarkupString)script)
@code {
string script = "<script data-main="payment-js" src="gateway.tillpayments.com/js/integrated/…>";
}
Old answer:
You could use the special HeadContent
component to add the script in the <head>
tag from your component.
<HeadContent>
<script suppress-error="BL9992" data-main="payment-js" src="gateway.tillpayments.com/js/integrated/…>
</HeadContent>
You have to add attribute suppress-error="BL9992"
so that it won't give you Error RZ9992.
Also there is this library for loading scripts in blazor: https://github.com/excubo-ag/Blazor.ScriptInjection
Upvotes: 4