1

I am trying to call a function every time a page is loaded. With Drupal 7, I used hook_init, now I'm using a subscribed event.

  public function logRegEntry(GetResponseEvent $event) {
    $request = $event->getRequest();
    $method = $request->getMethod();
    $path = $request->getPathInfo();
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (($method == 'GET') && ($path == '/')) {
      // do it just for this module
      \Drupal::service('wdocsDebug')->logSiteEntry();
    }
  }

This works fine for the home page, but I want it for every page a user requests. This is getting called four times; first for the page I'm requestings, and then for: /admin/coffee/get-data /history/5/read /quickedit/attachments

I did notice that on the first request, the $route_name is set to "entity.node.canonical" -- might this be a better way to check for a page? Probably not, since it would only get triggered by node pages.

I'm looking for a better way to do this, not sure why there are four request events. Thanks.

1

Your event subscriber is also picking up AJAX requests (e.g. /admin/coffee/get-data is an endpoint the Coffee module uses when it's needed in the client browser) which explains why you're seeing multiple events for a page request.

You can filter out those events with the logic best fits your needs (e.g. a $request->isXmlHttpRequest() call to check for AJAX requests, or a route whitelist as you mentioned).

1
  • Thanks, just what I was looking for.
    – pglatz
    Oct 29 '20 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.