question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to render script inside blazor component

See original GitHub issue

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I’m trying to embed github gist in my .net 6 blazor wasm application. <script> tag in general is not allowed inside blazor component. so I added it as MarkupString as shown below,

@(new MarkupString(@"<script src=""https://gist.github.com/fingers10/44eb8a5a5427b472d1c48ecb1b4268f7.js""></script>"))

But the rendered output is empty. When I inspected the html using browser, no such content is present in html.

Expected Behavior

Script should be added in html document and needs to be executed for github gist to be rendered.

Steps To Reproduce

  1. Create new blazor wasm project.
  2. Create a new component.
  3. Add the following MarkupString in the component html @(new MarkupString(@"<script src=""https://gist.github.com/fingers10/44eb8a5a5427b472d1c48ecb1b4268f7.js""></script>"))
  4. Run the application.

Exceptions (if any)

No response

.NET Version

6.0.101

Anything else?

No response

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
fingers10commented, Jan 18, 2022

@KristofferStrube I ended up improving your answer as component,

GithubGistSnippet.razor:

@inherits GithubGistSnippetBase

<section class="[ flex flex-col ]">
    <h4 class="[ bg-gray-200 ] [ p-2 ] [ font-semibold ] [ text-black ] [ flex items-center ]">
        <svg xmlns="http://www.w3.org/2000/svg" class="[ icon icon-tabler icon-tabler-code ] [ text-purple-700 ] [ fill-purple-500 ]" width="20" height="20" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
            <polyline points="7 8 3 12 7 16"></polyline>
            <polyline points="17 8 21 12 17 16"></polyline>
            <line x1="14" y1="4" x2="10" y2="20"></line>
        </svg> Code Sample - @Title
    </h4>
    <article id="@Id" class="[ bg-gray-300 ]">
    </article>
</section>

GithubGistSnippet.razor.cs:

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace Web.Components;

public class GithubGistSnippetBase : ComponentBase, IAsyncDisposable
{
    private IJSObjectReference? module;

    protected string Id = Guid.NewGuid().ToString();

    [Inject] private IJSRuntime JSRuntime { get; set; } = default!;

    [Parameter, EditorRequired] public string Title { get; set; } = default!;
    [Parameter, EditorRequired] public string UserId { get; set; } = default!;
    [Parameter, EditorRequired] public string FileName { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/githubgist.js");

        await module.InvokeVoidAsync("printSnippetFrom", Id, UserId, FileName);
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }
}

githubgist.js:

export function printSnippetFrom(id, userId, filename) {
    const target = document.getElementById(id);
    const iframe = document.createElement('iframe');
    const iframeId = `${userId}-${filename}`;
    iframe.setAttribute("id", iframeId);
    iframe.setAttribute("width", "100%");
    target.appendChild(iframe);

    let doc = iframe.document;
    if (iframe.contentDocument) doc = iframe.contentDocument;
    else if (iframe.contentWindow) doc = iframe.contentWindow.document;

    const gistScript = `<script src="https://gist.github.com/${userId}/${filename}.js"></script>`;
    const resizeScript = `onload="parent.document.getElementById('${iframeId}').style.height=document.body.scrollHeight + 'px'"`;
    const iframeHtml = `<html><body ${resizeScript}>${gistScript}</body></html>`;

    doc.open();
    doc.writeln(iframeHtml);
    doc.close();
}

Usage:

<GithubGistSnippet Title="DeSerialization" UserId="fingers10" FileName="44eb8a5a5427b472d1c48ecb1b4268f7"></GithubGistSnippet>

Output: GithubGistSnippet Component Output

1reaction
KristofferStrubecommented, Jan 17, 2022

Hey @fingers10 if you need af workaorund for now then this works:

@inject IJSRuntime JSRuntime

@JSRuntime.InvokeVoidAsync("document.write", @"<script src=""https://gist.github.com/fingers10/44eb8a5a5427b472d1c48ecb1b4268f7.js""></script>")
Read more comments on GitHub >

github_iconTop Results From Across the Web

.net - Blazor WASM Script tags should not be placed inside ...
Blazor WASM Script tags should not be placed inside components because they cannot be updated dynamically. Move the script tag to the index.html ......
Read more >
ASP.NET Core Blazor JavaScript interoperability (JS interop)
This article explains general concepts on how to interact with JavaScript in Blazor apps. A Blazor app can invoke JavaScript (JS) functions ...
Read more >
Adding script references in Blazor
Learn here about that how to add the script references manually in the Syncfusion Blazor Components.
Read more >
JavaScript Errors - Telerik UI for Blazor
Troubleshooting JavaScript errors in the UI for Blazor suite. ... As a result, the script does not include all components, features or correct...
Read more >
How to run code after Blazor component has rendered
This blog post will show you how to run code after your Blazor component has rendered, on every render or as needed. Sample...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found