Skip to content

Instantly share code, notes, and snippets.

@swissspidy
Created September 11, 2024 15:26
Show Gist options
  • Save swissspidy/a51a13eb5b6236ed7a1dfcaebfd4080b to your computer and use it in GitHub Desktop.
Save swissspidy/a51a13eb5b6236ed7a1dfcaebfd4080b to your computer and use it in GitHub Desktop.
Example transformer to add a "nonce" attribute to script tags in stories
<?php
/**
* Plugin Name: Web Stories CSP nonce transformer example
* Description: Example transformer to add a "nonce" attribute to script tags in stories.
* Author: Pascal Birchler
* Author URI: https://pascalbirchler.com/
* Version: 0.0.1
* Requires at least: 6.4
* Requires PHP: 7.4
* License: Apache License 2.0
* License URI: https://www.apache.org/licenses/LICENSE-2.0
*
* @copyright 2023 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action(
'init',
static function() {
if ( ! interface_exists( '\Google\Web_Stories_Dependencies\AmpProject\Optimizer\Transformer' ) ) {
return;
}
add_filter(
'web_stories_amp_optimizer_config',
static function ( $config ) {
$config['transformers'][] = Your_Website_Example_CSP_Nonce_Transformer::class;
return $config;
}
);
class Your_Website_Example_CSP_Nonce_Transformer implements \Google\Web_Stories_Dependencies\AmpProject\Optimizer\Transformer {
public function transform( \Google\Web_Stories_Dependencies\AmpProject\Dom\Document $document, \Google\Web_Stories_Dependencies\AmpProject\Optimizer\ErrorCollection $errors ) {
$scripts = $document->xpath->query( '//script[ not( @type ) or @type = "module" ]' );
foreach ( $scripts as $script ) {
/** @type \DOMElement $script */
$script->setAttribute( 'nonce', 'fooo' );
}
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment