79121059

Date: 2024-10-24 08:42:21
Score: 0.5
Natty:
Report link

I was recently trying to do the same thing with my "Buy Me a Coffee" button, where I only wanted it on certain pages. I'm not enough of an expert with JavaScript (and even Blazor) to understand what really happens, but I only understand enough to know that the external JS script must be called when the WebAssembly loads, for the widget to appear.

Specifically for a Blazor WebAssembly, the external script must be included in the wwwroot/index.html as a script tag. But by doing so, this widget appears on all pages of your website.

I then tried working with JS Interop to call that external script via a self-written JavaScript function, only when certain pages are initialized and although that technically worked (i.e. the self-written JavaScript function was called), the widget however never appeared.

I finally thought of a "hack", where I simply included the external script as usual in wwwroot/index.html, but then accessed the div container of that widget via its ID and just setting the visibility to "hidden" or "visible".

Here's how I did it. The first step was to define that JS function:

// wwwroot/js/scripts.js
function HideBuyMeaCoffeeButton(id) {
    var buttonDivObject = document.getElementById(id);
    buttonDivObject.style.visibility = "hidden";
}
function ShowBuyMeaCoffeeButton(id) {
    var buttonDivObject = document.getElementById(id);
    buttonDivObject.style.visibility = "visible";
}

Next, for the (Razor) pages where you would like to hide the widget:

@inject IJSRuntime JSRuntime
@implements IAsyncDisposable

// <your content>

@code {
    private IJSObjectReference? module;
    
    // Turn "off" the Buy Me a Coffee button
    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/scripts.js");
        }
        await HideOffBuyMeaCoffeeButton();
    }
    private async Task HideOffBuyMeaCoffeeButton()
    {
        // My widget div container had the ID: 'bmc-wbtn'
        await JSRuntime.InvokeVoidAsync("HideBuyMeaCoffeeButton", "bmc-wbtn");
    }
    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null){await module.DisposeAsync();}
    }
}

And for the (Razor) pages where you would like to show the widget, simply swap HideBuyMeaCoffeeButton with ShowBuyMeaCoffeeButton. It isn't perfect but it works well enough for my hobby project, where I only have the widget on my "Blogs".

Reasons:
  • Blacklisted phrase (1): trying to do the same
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: RenZhen95