Ive tried several ways of getting the previous page url and what link they clicked on within a twig file. How do you accomplish this from a twig in Drupal9.
I have tried the following JS in twig but its not rendering.
<script type="text/javascript">
document.write(document.referrer);
</script>
I had solved it by using JQuery. It's for building a mailto: string that auto populated an email with what link a user clicked on and what page they came from on a page 404. When they hit contact us it prepares a nice email.
First, in Drupal setup the correct page suggestion for error handling:
$route_name = \Drupal::routeMatch()->getRouteName();
switch ($route_name) {
case 'system.401':
// Unauthorized Access.
$error = 401;
break;
case 'system.403':
// Access Denied.
$error = 403;
break;
case 'system.404':
// Page Not Found.
$error = 401;
break;
case 'system.500':
// Something went wrong.
$error = 401;
break;
case 'system.503':
// Service unavailable.
$error = 503;
break;
case 'system.504':
// Gateway timeout.
$error = 504;
break;
}
if (isset($error)) {
$suggestions[] = 'page__' . $error;
}
}
The JQuery:
$('body a').on('click', function(){
localStorage.setItem('clickedURL', $(this).attr("href"));
});
Unless someone has a better way please share.