Skip to content

Instantly share code, notes, and snippets.

@szeidler
Created July 5, 2021 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szeidler/38be2ae02e29d78bffeddf92bf90cbe3 to your computer and use it in GitHub Desktop.
Save szeidler/38be2ae02e29d78bffeddf92bf90cbe3 to your computer and use it in GitHub Desktop.
Whitelist specific pages for iframe embedding by removing the X-Frame-Options header in Drupal
<?php
// REMOVE ME: Place in /web/modules/custom/mymodule/src/EventSubscriber/EmbedSubscriber.php
namespace Drupal\mymodule_embed\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class EmbedSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['onRespond'];
return $events;
}
/**
* Removes the X-Frame-Options http header for specific URIs.
*
* Used to allow iframe embeds and prevent same origin
* policy problems in the browser.
*
* @param FilterResponseEvent $event
*/
public function onRespond(FilterResponseEvent $event) {
$response = $event->getResponse();
$whitelistedUris = ['/path1whitelist', '/path2whitelist'];
if (in_array($event->getRequest()->getRequestUri(), whitelistedUris)) {
$response->headers->remove('X-Frame-Options');
}
}
}
name: Mymodule Embed
description: Whitelists specific pages to be possible to embed as an iframe.
package: Custom
type: module
core_version_requirement: ^8 || ^9
services:
mymodule_embed:
class: '\Drupal\mymodule_embed\EventSubscriber\EmbedSubscriber'
tags:
- { name: 'event_subscriber' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment