1

I need to clear the stateParams (search parameters) from Url if a user reloads the page or refreshes it. I am using AngularJS 1.5.8.

I can detect the reload/refresh event and can even output to console, but the code to remove the search parameters doesn't fire. Here's what I am using

var windowElement = angular.element($window);
windowElement.on('beforeunload', function (event) {
    $location.url($location.path());
    console.info("page refreshed." + $location.path());        
});

Any pointers?

user869375
  • 2,299
  • 5
  • 27
  • 46

2 Answers2

2

try

$location.search({});

to remove all params. If you want to remove specific ones, then

$location.search('key', null);

should do the trick.

Also, check out $destroy listener, which tells angular that on $destroy of a controller/directive, call this function.

$scope.$on('$destroy', function () {
   $location.search({});
});

Not much in the docs...but it's here.

Harshith Rai
  • 3,018
  • 7
  • 22
  • 35
fayzaan
  • 265
  • 3
  • 9
  • Tried $location.search({}); as well. But the code only fires when we close the browser window but not on page reload. The weird thing is that the console output is logged both at refresh/reload as well as browser close events. – user869375 Jul 03 '19 at 06:34
1

Hope this helps others, As none of the suggestions I saw on SO worked. I managed to create kind of a hack to get this working using the following code in app.run function.

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    //not coming from any other page + coming to ads page + contains query string
    if (fromState.name == "" && toState.name == "current_page" && toState.url !== "/current-page-url") {
        $location.search({});
    }
});

What it does is if I come to the page from other pages, it will have fromState populated but when I reload the current page, the fromState will have no data and toState will the details of the current page. To avoid continuous looping, I also check if the current url contains any querystring.

UPDATE Even a better solution. Found some help from this link.

$rootScope.$on("$locationChangeStart", function (event, next, current) {
        //Page reload detection
        if (next == current && && performance.navigation.type == 1) {
            event.preventDefault();
            $location.search({});
        }
    });

The first solution removes the query string even when you load a page with query string for the first time (via some bookmark).

The second solution works just as intended.

See this for reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/performance

user869375
  • 2,299
  • 5
  • 27
  • 46