How do I open a browser window/tab from blazor webassembly project behind code:
Asked Answered
C

4

6

I'm converting a UWP app to Blazor WebAssembly with ASP.NET Core hosted.

I have my markup code in Index.razor and behind code in Index.razor.cs.

In the UWP project I opened a browser window from an onclick function like this:

var success = Windows.System.Launcher.LaunchUriAsync(targetPage);

What can I use in my Blazor project onclick event, that won't lead to "unhandled error has occurred"?

Chasten answered 5/5, 2020 at 20:21 Comment(3)
You'll need to use JS interop for this.Soiree
Maybe you can use a <a target="_blank" instead ?Cerous
these should be answers. For the js interop - window.open(url) is your friend.Delindadelineate
A
15

You can open a tab by making use of the 'window.open' function:

@inject IJSRuntime JSRuntime;
....
await JSRuntime.InvokeAsync<string>("open", $"https://www.mysite/mypage", "_blank");

if the page is internal to your website you can use the base uri:

@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime;
...
await JSRuntime.InvokeAsync<string>("open", $"{Navigation.BaseUri}/mypage", "_blank");
Angrist answered 10/8, 2020 at 18:37 Comment(0)
S
3

These are great answers and I took it one step further to make a re-usable component. My app uses anchors and link buttons so I have a quick-and-dirty switch for each.

ExternalLink.razor

@inject IJSRuntime JSRuntime

@if (Type == "link") 
{
    <a href="" @onclick="OpenWindow">@(Text ?? Url)</a>
}
else if (Type == "button") 
{
    <button type="button" class="btn btn-link" @onclick="OpenWindow">@(Text ?? Url)</button>
}

@code {
    [Parameter]
    public string Url { get; set; }

    [Parameter]
    public string Text { get; set; }

    [Parameter]
    public string Type { get; set; } = "link";

    private async Task OpenWindow() 
    {
        await JSRuntime.InvokeAsync<string>("open", Url, "_blank");
    }
}

Usage

<ExternalLink Url="https://www.ourwebsite.com/" Text="Visit Us!" />
<ExternalLink Url="https://stackoverflow.com/" />
<ExternalLink Url="https://duckduckgo.com/" Type="button" />
Subtotal answered 1/7, 2022 at 19:1 Comment(0)
A
0

You case use below way

razor file

JSRuntime.InvokeVoidAsync("OpenWindow");

html file

<script>
        function OpenWindow() {
            window.open('https://www.google.com', 'Test', 'width=800,height=860,scrollbars=no,toolbar=no,location=no');
            return false
        }
        </script>
Apthorp answered 27/7, 2020 at 8:29 Comment(0)
C
-2

Why not just use the build in NavigationManager?

Navigation.NavigateTo(a_url, true);

The trick is to use the force parameter.

Happy coding.

Careaga answered 15/4, 2021 at 7:50 Comment(1)
While NavigationManager supports redirect, it cannot open the URL in a new window.Embosom

© 2022 - 2025 — McMap. All rights reserved.