I have a controller that inject a phtml via the
$this->_view->getLayout()->getBlock('block_name')->toHtml();
code. The problem is that the template for this block has an inline javascript. I have tried to use the secure renderTag()
method but it doesn’t work: when I inspect the page on the browser, instead of having the tag <script nonce>
, I have the normal tag <script>
as the render tag wasn’t there. Eg, this is the original phtml:
<?php
// some php code
?>
<div class="myclass">
<!-- some html content -->
</div>
<script>
require(['jquery'],function($){
$(document).ready(function() {
console.log('some text goes here');
});
});
</script>
This is the fixed template (the php and html parts are the same, I simply put the script part inside the renderTag
method):
<?php
// some php code
?>
<div class="myclass">
<!-- some html content -->
</div>
<?php
/** @var MagentoFrameworkViewHelperSecureHtmlRenderer $secureRenderer */
$scriptString = <<<script
require(['jquery'],function($){
$(document).ready(function() {
console.log('some text goes here');
});
});
script;
?>
<?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false) ?>
The fixed version should show up in the browser inspector as:
<script nonce>
require(['jquery'],function($){
$(document).ready(function() {
console.log('some text goes here');
});
});
</script>
Instead, it just shows as plainly:
<script>
require(['jquery'],function($){
$(document).ready(function() {
console.log('some text goes here');
});
});
</script>
and of course the browser is throwing a csp error message.
Is there a way to whitelist this kind of inline scripts?