Run some code when leaving page

Hello. How can I run some code when leaving a specific page? I tried this hook:

'route:after' => function($route, $path, $method, $result, $final) {
  if ($path !== 'checkout') {
    removeAllShipping();
  }
}

to run this code after leaving the checkout page, and it works, but is there a better way? The above will needlessly be executed for every page change.

I don’t have insight in your website’s architecture, but maybe reverse the logic? E.g.:

'route:after' => function($route, $path, $method, $result, $final) {
  if ($path == 'checkout') {
    addShipping();
  }
}

@bvdputte I guess not. This ‘shipping’ item is added when somebody enters the checkout page, and should be removed when she/he leaves.

does the shipping really have to be removed when you leave the page? you could simply removeAllShipping before entering the route where the user gets to addShipping again. I guess this is kind of what @bvdputte already suggested.

otherwise if your route works, maybe just throw in another condition so the entire function doesn’t have to be called on each load (assuming removeAllShipping() is a little bit more complex)

if ($path !== 'checkout' && $hasShipping) {
    removeAllShipping();
}

and call it a day :smiley:

You are both right. Thanks!