You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AngularJS中针对特定路由设置/移除localStorage?

Solution for Managing localStorage on Route Load/Tab Close in AngularJS

Got it, let's fix this up properly. Your current code sets the user localStorage item when the /user route loads, but it doesn't handle cleaning it up when the tab is closed. Here's a complete implementation that meets your requirements:

Step 1: Update the User Controller

We need to add two key things: a listener for the tab close/unload event, and cleanup when the user navigates away from the /user route within the app.

var app = angular.module('Test', ['ngResource', 'ngRoute']);

app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider){
  $locationProvider.hashPrefix('');
  $routeProvider
    .when('/', { templateUrl: 'home.html' })
    .when('/user', { templateUrl: 'user.html', controller: 'User' })
    .otherwise({ redirectTo: '/' });
}]);

app.controller('User', function($scope) {
  // Set localStorage when entering the /user route
  localStorage.setItem('user', "true");

  // Function to remove the localStorage item
  function cleanUpUserStorage() {
    localStorage.removeItem('user');
  }

  // Listen for tab close/refresh events
  window.addEventListener('beforeunload', cleanUpUserStorage);

  // Remove the listener when leaving the /user route (controller destroys)
  // This prevents accidental cleanup when navigating to other routes in the same tab
  $scope.$on('$destroy', function() {
    window.removeEventListener('beforeunload', cleanUpUserStorage);
  });
});

How This Works

  • Route Entry: When the user navigates to /user, the controller initializes and sets localStorage.setItem('user', "true"), making this value available across the entire app.
  • Tab Close/Refresh: The beforeunload event fires when the tab is closed, refreshed, or the user navigates to an external site—this triggers cleanUpUserStorage() to remove the user item.
  • Internal Route Navigation: When the user moves from /user to another route in the same tab, the controller's $destroy event fires, which removes the beforeunload listener. This ensures we don't accidentally delete the user item if the user later closes the tab from a different route.

Important Note

Since localStorage is shared across all tabs for the same origin, closing one /user tab will remove the user value for all other tabs. If you need the user value to persist as long as any /user tab is open, consider using sessionStorage (which is tab-specific) instead, or add additional logic to track active tabs using the storage event.

内容的提问来源于stack exchange,提问作者its me

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:54:57