Opening link in new tab from Blazor Server

259 Views Asked by At

I'm trying to open a link in a new tab from a Blazor Server application. I tried several methods such as

await JSRuntime.InvokeVoidAsync("open", action.ActionData, "_blank");

as well as

await JSRuntime.InvokeVoidAsync("NavigateTo", action.ActionData);

whereas the NavigateTo function appears as follows:

window.NavigateTo = (url) => {
    const link = document.createElement('a');
    link.href = url;
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    link.remove();
}

Everything is working fine in all browsers except for Safari on IOS.

Has anybody found a solution to this problem? As I found out, there is a problem opening a new tab in Safari from an asynchronous task. But I couldn't find a way to start this synchronously from Blazor Server.

2

There are 2 best solutions below

0
M4SX5 On BEST ANSWER

I found a quite simple answer to my problem. As the tab stays open, I could just execute the action in a onclick event and add a href attribute to the link with the target="_blank" attribute.

<a @onclick="ExecuteBackgroundTask" href="https://link.to.newpage" target="_blank" rel="noopener noreferrer">
    Click there to open link in new tab and execute some work in the background.
</a>

The browser will open the link in a new tab and execute the action in the background in the old tab.

2
Bennyboy1973 On

This is a deliberate feature by the browser, blocking you from doing something obnoxious with your code. People definitely don't WANT a site they visit to just start spawning new pages whenever it wants to. You might spawn one page, or you might spawn a dozen popup ads.

The minimum requirement for almost any mobile media is that it is initialized in a legitimate UI interaction-- say, the actual (not simulated) click of a button on the client screen.

Most of my sites have an "ENTER SITE" button and nothing else on the front page. I use this to preload audio, request media recorder permissions, etc. It's a hack and a bit of a dirty trick, but it allows me to sync audio with images in slideshows and so on.

So I suggest you do as much of the link initialization as you can in a click handler in javascript, rather than in Blazor interop calls.