How to test if current page is an admin page?
* Updated *

When I first answered this question, node edit and taxonomy edit pages weren't set as admin routes.  So I added separate checks for those.  Such separate checks aren't necessary any more.  The following seems to cover it pretty well:

if (\Drupal::service('router.admin_context')-&gt;isAdminRoute()) {
 // do stuff
}


If you want to check a route other than the current route, you can pass it into isAdminRoute().

Note, the above way won't work for node edit pages or taxonomy term edit pages if you uncheck "Use the administration theme when editing or creating content" on the theme admin page at /admin/appearance.  Then you'd need a separate check.

* Original Answer: *

To test if a page is an admin page, you can use a two step process.  Since regex for the node edit may not be using the admin theme.

First I use the isAdminRoute method:

  $route = \Drupal::routeMatch()-&gt;getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')-&gt;isAdminRoute($route);


Then you can use an additional check for the path to see if it's a node edit page:

  $current_path = \Drupal::service('path.current')-&gt;getPath();
  if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
    $is_admin = TRUE;
  }


Here's a pretty elaborate, but pretty complete way to test for node and taxonomy term edit pages as well as other admin routes:

  $route = \Drupal::routeMatch()-&gt;getRouteObject();

  $is_admin = FALSE;
  if (!empty($route)) {
    $is_admin_route = \Drupal::service('router.admin_context')-&gt;isAdminRoute($route);
    $has_node_operation_option = $route-&gt;getOption('_node_operation_route');
    $is_admin = ($is_admin_route || $has_node_operation_option);
  }
  else {
    $current_path = \Drupal::service('path.current')-&gt;getPath();
    if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
    elseif(preg_match('/taxonomy\/term\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
  }