Hi,
How to identify if the first page of the website is refreshed in the same tab or the page is loading at the first time in asp.net mvc. If the page is opened in the different browser or tab, it should show an alert message and close the browser/tab.

Uday DodiyaRank #239 · 10.3K reputationPosted Sep 7, 2024, 5:14 AM EDT
Hi, Anu
you can achive both output like for Detecting Page Load or Refresh & Show Alert and Close Tab if Page is Opened in a New Tab/Browser using sessionStorage.
Add this JavaScript code in your MVC View (demo.cshtml )
// Check if the page is loaded for the first time in this tab or browser window if (!sessionStorage.getItem('pageLoaded')) { sessionStorage.setItem('pageLoaded', 'true'); console.log('Page loaded for the first time'); } else { console.log('Page refreshed or already loaded'); } // Logic to detect if the page is opened in a new tab or browser if (!localStorage.getItem('uniquePageLoad')) { alert("This page has been opened in a new tab or browser."); window.close(); } else { console.log('Page loaded in the same session'); } localStorage.setItem('uniquePageLoad', 'true');Aman GuptaRank #193 · 12.4K reputationPosted Sep 7, 2024, 1:52 PM EDT
Hi Anu,
If you are trying to identify if a page in ASP.NET MVC is being refreshed or if it's being loaded for the first time (in the same tab or a new tab/browser), you can use a combination of server-side and client-side techniques.
The basic idea is to track whether the page has been previously visited in the same session or not.
You can find it using Session, localStorage, and JavaScript:
Steps:
Example:
Controller (ASP.NET MVC):
public class HomeController : Controller { public ActionResult Index() { // Check if the page is loaded for the first time in the session if (Session["FirstLoad"] == null) { Session["FirstLoad"] = true; } return View(); } }View (Razor View
Index.cshtml):@{ // Check if the session is loaded for the first time var isFirstLoad = Session["FirstLoad"] != null; } Home Page // Function to handle page refresh or new tab detection window.onload = function () { var isFirstLoad = @isFirstLoad.ToString().ToLower(); // Check if page is being opened in a new tab/browser if (!localStorage.getItem('PageLoaded')) { // Page loaded for the first time in this browser/tab localStorage.setItem('PageLoaded', 'true'); } else if (isFirstLoad === "true") { // Page is refreshed or reloaded console.log('Page refreshed'); } else { // Show alert for new tab/browser and close it alert("This page is already open in another tab. Closing this tab..."); window.close(); // Close the current tab } }; // Handle unload event to remove localStorage item when the tab is closed window.onunload = function () { localStorage.removeItem('PageLoaded'); }; Welcome to the Home Page!Explanation:
This will help you Anu, in detecting First Login or refreshed login.
Thanks
Shweta LodhaRank #31 · 39.8K reputationPosted Sep 8, 2024, 8:05 PM EDT
Here are the 2 ways: