I am working on a Drupal website and I need to implement a functionality where an iframe is opened with a different base URL whenever a "Page Not Found" error occurs. The goal is to display the content from a different website within the iframe.
I have tried implementing a custom module using the hook_preprocess_HOOK() and hook_page_attachments() hooks, but I'm encountering issues with the code not running when a "Page Not Found" error occurs.
Here is an example of the code I have tried:
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Implements hook_preprocess_HOOK() for page templates.
*/
function iframe_error_preprocess_page(&$variables) {
// Check if the current page is a "Page Not Found" error.
$exception = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
echo"<h1>INSIDE FUNCTION</h1>";
if (!($exception instanceof NotFoundHttpException)) {
echo"<h1>INSIDE 404</h1>";
// Get the base URL of the iframe.
$iframe_base_url = 'https://usj2.edu.lb';
// Get the current URL.
$current_url = \Drupal::request()->getUri();
// Replace the base URL in the current URL.
$iframe_url = str_replace('https://usj-dev.usj.edu.lb', $iframe_base_url, $current_url);
// Build the iframe markup.
$iframe_markup = '<iframe src="' . $iframe_url . '" width="100%" height="100%"></iframe>';
// Assign the iframe markup to a variable for use in the page template.
// $variables['iframe_markup'] = $iframe_markup;
echo $iframe_markup;
}
}
Your help is appreciated.