Skip to content
Snippets Groups Projects

#3182213 Add crossorigin attribute to script tags

Open #3182213 Add crossorigin attribute to script tags
3 unresolved threads
Open Daniel Kulbe requested to merge issue/cdn-3182213:3182213-crossorigin-attribute into 4.x
3 unresolved threads
@@ -33,6 +33,8 @@ class HtmlResponseSubscriber implements EventSubscriberInterface {
}
$this->addPreConnectLinkHeaders($response);
$this->addScriptCrossOrigin($response);
}
/**
@@ -49,6 +51,36 @@ class HtmlResponseSubscriber implements EventSubscriberInterface {
}
}
/**
* Adds crossorigin attribute to script tags.
*
* @param \Drupal\Core\Render\HtmlResponse $response
* The HTML response to update.
*
* @see https://www.w3.org/TR/2014/REC-html5-20141028/scripting-1.html#attr-script-crossorigin
Please register or sign in to reply
*/
protected function addScriptCrossOrigin(HtmlResponse $response): void {
$content = $response->getContent();
foreach ($this->settings->getDomains() as $domain) {
$pattern = '/<script src="(?:https?:)?\/\/' . quotemeta($domain) . '\/.*"/';
Please register or sign in to reply
$content = preg_replace_callback($pattern, [$this, 'updateScriptTag'], $content);
}
$response->setContent($content);
}
/**
* Callback to replace individual script links.
*
* @param array $matches
* Array from matches from preg_replace_callback.
*
* @return string
* Updated HTML string.
*/
protected function updateScriptTag(array $matches): string {
return "{$matches[0]} crossorigin";
}
/**
* {@inheritdoc}
*/
Loading