I’m working on a Blazor WebAssembly application and encountering an issue where the same page can be opened in multiple tabs if the user either copies the URL or modifies the link in the browser. I want to prevent this behavior and ensure that if a tab with a specific URL is already open, a new tab with the same URL should not be opened.
Here’s what I’ve tried so far:
Using sessionStorage: I tried storing a flag in sessionStorage indicating that a particular URL is open. However, this approach doesn’t work when the user copies the URL into a new tab.
Handling navigation events: I attempted to handle the navigation events (@code OnInitializedAsync or NavigationManager.LocationChanged) to check if the URL is already open in another tab. But I couldn’t figure out how to reliably detect if the URL is open in another tab.
Is there a way to reliably prevent duplicate tabs in a Blazor WebAssembly application? Any help or guidance on approaching this problem would be greatly appreciated.
@page "/"
@inject IJSRuntime JSRuntime
<h3>My Component</h3>
@code {
@inject NavigationManager nav ;
protected override async Task OnInitializedAsync()
{
var url = nav.Uri;
// Check if URL is already in session storage
var isInSessionStorage = await JSRuntime.InvokeAsync<bool>("checkIfURLInSessionStorage", url);
if (!isInSessionStorage)
{
// URL already visited, show alert
await JSRuntime.InvokeVoidAsync("alert", "This URL is already opened in another tab!");
await JSRuntime.InvokeVoidAsync("closeWindow");
return; // Stop further execution
}
}
}
Duplicate.js
window.checkIfURLInSessionStorage = function (url) {
var visitedURLs = JSON.parse(sessionStorage.getItem("visitedURLs")) || [];
// Check if the URL is in visitedURLs
if (visitedURLs.includes(url))
{
// If the URL is already in visitedURLs, return false
return false;
}
// If the URL is not in visitedURLs, add it to sessionStorage
visitedURLs.push(url);
sessionStorage.setItem("visitedURLs", JSON.stringify(visitedURLs));
// Return true since the URL was not found in visitedURLs
return true;
};
window.closeWindow = function closeWindow()
{
window.close();
}
Expected Behavior:
When a user tries to open a page that is already open in another tab (either by copying the URL or modifying the link in the browser), the existing tab should be focused instead of opening a new tab.
Environment:
Blazor WebAssembly
.NET 7.0
Visual Studio 2022
Browser: All browsers