How to generate masquerade link programmatically

Components

The Masquerade module allows website admins to switch users and visit the website as that user. This is helpful for developers and site builders when trying to find out what a client might see when logged into the website. To create the unmasquerade programmatically use this:

if (
  \Drupal::moduleHandler()->moduleExists('masquerade') && 
  \Drupal::service('masquerade')->isMasquerading()
){
  $links['unmasquerade'] = [
    '#type' => 'link',
    '#title' => t('Unmasquerade'),
    '#url' => Url::fromRoute('masquerade.unmasquerade'),
    '#weight' => 1500,
  ];
}

About the Author

Goran Nikolovski is a senior web developer who loves working with Drupal, React, and React Native. He is the founder of this website and he enjoys sharing his knowledge. Need help with anything? Get in touch.