Skip to content

Commit

Permalink
render inline scripts with secure renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
Joris Wagter committed Jul 10, 2024
1 parent 3c34d66 commit d09f5d3
Show file tree
Hide file tree
Showing 5 changed files with 172 additions and 127 deletions.
31 changes: 20 additions & 11 deletions view/frontend/templates/add-to-cart-event.phtml
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
<?php /** @var \Magento\Framework\View\Element\Template $block */ ?>
<?php
/** @var \Magento\Framework\View\Element\Template $block */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<script>
require(['jquery'], function ($) {
<?php
$script = <<<JS
$(document).on('ajax:addToCart', function (event, data) {
taggrsAjaxEvent('addtocart').then(() => {
taggrsReloadQuoteData();
});
});
require(['jquery'], function ($) {
$("[data-block=\"minicart\"]").on("dropdowndialogopen", function ( e ) {
taggrsAjaxEvent('viewcart', () => {}, 1);
$(document).on('ajax:addToCart', function (event, data) {
taggrsAjaxEvent('addtocart').then(() => {
taggrsReloadQuoteData();
});
});
</script>
$("[data-block=\"minicart\"]").on("dropdowndialogopen", function ( e ) {
taggrsAjaxEvent('viewcart', () => {}, 1);
});
});
JS;
?>

<?= /* @noEscape */ $secureRenderer->renderTag('script', ['type' => 'text/javascript'], $script, false); ?>
30 changes: 20 additions & 10 deletions view/frontend/templates/checkout-js.phtml
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
<script>
<?php
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?php
$script = <<<JS
require([
'Magento_SalesRule/js/action/set-coupon-code',
'Magento_SalesRule/js/model/coupon',
'Magento_Checkout/js/model/quote'
],
function (setCouponCode, coupon, quote) {
setCouponCode.registerSuccessCallback((response) => {
taggrsAjaxEvent('selectpromotion');
});
'Magento_SalesRule/js/action/set-coupon-code',
'Magento_SalesRule/js/model/coupon',
'Magento_Checkout/js/model/quote'
],
function (setCouponCode, coupon, quote) {
setCouponCode.registerSuccessCallback((response) => {
taggrsAjaxEvent('selectpromotion');
});
</script>
});
JS;
?>

<?= /* @noEscape */ $secureRenderer->renderTag('script', ['type' => 'text/javascript'], $script, false); ?>
30 changes: 19 additions & 11 deletions view/frontend/templates/data-layer.phtml
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
<?php /** @var \Taggrs\DataLayer\Block\DataLayer $block */
/** @var \Magento\Framework\Escaper $escaper */
<?php
/** @var \Taggrs\DataLayer\Block\DataLayer $block */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */

$dataLayer = $block->getDataLayer();
$jsonDatalayer = /* @noEscape */ json_encode($block->getDataLayer());
?>
<script>
(function () {
document.addEventListener('DOMContentLoaded', () => {
const dataLayer = <?= /* @noEscape */ json_encode($dataLayer); ?>;
taggrsPush(dataLayer, true);
});
})();
</script>

<?php
$script = <<<JS
(function () {
document.addEventListener('DOMContentLoaded', () => {
const dataLayer = $jsonDatalayer;
taggrsPush(dataLayer, true);
});
})();
JS;
?>

<?= /* @noEscape */ $secureRenderer->renderTag('script', ['type' => 'text/javascript'], $script, false); ?>
204 changes: 111 additions & 93 deletions view/frontend/templates/gtag.phtml
Original file line number Diff line number Diff line change
@@ -1,128 +1,146 @@
<?php
/** @var \Taggrs\DataLayer\Block\Gtag $block */
/** @var \Magento\Framework\Escaper $escaper */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?php
if ( ! empty( $block->getGtmCode() ) ) {
$url = $escaper->escapeJs( $escaper->escapeUrl( $block->getGtmUrl() ) );
$gtmCode = $escaper->escapeHtml( $block->getGtmCode() );

$gtmTagScript = <<<JS
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src=
'https://$url/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','$gtmCode');
JS;

$url = $block->getGtmUrl();
$gtmCode = $block->getGtmCode();
echo /* @noEscape */ $secureRenderer->renderTag( 'script', [ 'type' => 'text/javascript' ], $gtmTagScript, false );
}
?>
<?php if (!empty($block->getGtmCode())): ?>
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src=
'https://<?= $escaper->escapeJs($escaper->escapeUrl($url)); ?>/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','<?= $escaper->escapeHtml($gtmCode); ?>');
</script>
<?php endif; ?>
<script>

window.taggrsQuoteData = {};
window.taggrsCurrency = '<?= $escaper->escapeJs($escaper->escapeHtml($block->getCurrency())) ?>';
window.taggersEventsConfig = <?= /* @noEscape */$block->getAjaxEventsConfig(); ?>;
<?php
$currency = $escaper->escapeJs( $escaper->escapeHtml( $block->getCurrency() ) );
$eventsConfig = /* @noEscape */
$block->getAjaxEventsConfig();
$debugMode = $escaper->escapeJs( $block->isDebugMode() ? 'true' : 'false' );
$quoteDataUrl = $escaper->escapeUrl( $block->getUrl( 'taggrs-datalayer/getquotedata' ) );
$userDataUrl = $escaper->escapeUrl( $block->getUrl( 'taggrs-datalayer/getuserdata' ) );
$ajaxBaseUrl = $escaper->escapeUrl( $block->getUrl( 'taggrs-datalayer' ) );
?>

window.taggrsDebugMode = <?= $escaper->escapeJs($block->isDebugMode() ? 'true' : 'false') ?>;
<?php
$helpersScript = <<<JS
document.addEventListener('DOMContentLoaded', () => {
taggrsReloadQuoteData();
});
window.taggrsQuoteData = {};
window.taggrsCurrency = '$currency';
window.taggersEventsConfig = $eventsConfig;
window.taggrsDebugMode = $debugMode;
const eventTriggeredCounter = {};
document.addEventListener('DOMContentLoaded', () => {
taggrsReloadQuoteData();
});
function taggrsReloadQuoteData() {
const eventTriggeredCounter = {};
return fetch('<?= $escaper->escapeUrl($block->getUrl('taggrs-datalayer/getquotedata')) ?>')
.then(response => {
function taggrsReloadQuoteData() {
return fetch('$quoteDataUrl')
.then(response => {
if (!response.ok) {
console.warn('GET request failed');
}
return response.json()
})
.then(data => {
window.taggrsQuoteData = data;
console.log('Quote data reloaded');
})
}
.then(data => {
window.taggrsQuoteData = data;
console.log('Quote data reloaded');
})
}
function taggrsLoadUserData(callback) {
return fetch('<?= $escaper->escapeUrl($block->getUrl('taggrs-datalayer/getuserdata')) ?>')
.then(response => {
if (!response.ok) {
console.warn('GET request failed');
}
return response.json()
})
.then(data => {
window.taggrsUserData = data;
if (typeof callback === 'function') {
callback(data);
}
})
}
function taggrsLoadUserData(callback) {
return fetch('$userDataUrl')
.then(response => {
if (!response.ok) {
console.warn('GET request failed');
}
return response.json()
})
.then(data => {
window.taggrsUserData = data;
if (typeof callback === 'function') {
callback(data);
}
})
}
function taggrsPush(dataLayer, reloadUserData) {
function taggrsPush(dataLayer, reloadUserData) {
if (!dataLayer.hasOwnProperty('ecommerce')) {
return;
}
if (!dataLayer.hasOwnProperty('ecommerce')) {
return;
}
window.dataLayer = window.dataLayer || [];
window.dataLayer = window.dataLayer || [];
if (!dataLayer.hasOwnProperty('ecommerce')) {
dataLayer.ecommerce = {};
}
if (!dataLayer.hasOwnProperty('ecommerce')) {
dataLayer.ecommerce = {};
}
const userDataEmpty = !dataLayer.ecommerce.hasOwnProperty('user_data')
|| !dataLayer.ecommerce.user_data.hasOwnProperty('email')
const userDataEmpty = !dataLayer.ecommerce.hasOwnProperty('user_data')
|| !dataLayer.ecommerce.user_data.hasOwnProperty('email')

if (userDataEmpty) {
taggrsLoadUserData((data) => {
dataLayer.ecommerce.user_data = data;
window.dataLayer.push(dataLayer);
if (window.taggrsDebugMode) {
console.log(dataLayer);
}
});
} else {
if (userDataEmpty) {
taggrsLoadUserData((data) => {
dataLayer.ecommerce.user_data = data;
window.dataLayer.push(dataLayer);
if (window.taggrsDebugMode) {
console.log(dataLayer);
console.log(dataLayer);
}
});
} else {
window.dataLayer.push(dataLayer);
if (window.taggrsDebugMode) {
console.log(dataLayer);
}


}
}
function taggrsAjaxEvent(eventName, callback, limit) {
function taggrsAjaxEvent(eventName, callback, limit) {
if (typeof limit !== "undefined") {
if (eventTriggeredCounter.hasOwnProperty(eventName) && eventTriggeredCounter[eventName] >= limit ) {
return;
}
if (typeof limit !== "undefined") {
if (eventTriggeredCounter.hasOwnProperty(eventName) && eventTriggeredCounter[eventName] >= limit ) {
return;
}
if (!eventTriggeredCounter.hasOwnProperty(eventName)) {
eventTriggeredCounter[eventName] = 1;
} else {
eventTriggeredCounter[eventName]++;
}
if (!eventTriggeredCounter.hasOwnProperty(eventName)) {
eventTriggeredCounter[eventName] = 1;
} else {
eventTriggeredCounter[eventName]++;
}
}
const ajaxBaseUrl = '<?= $escaper->escapeUrl($block->getUrl('taggrs-datalayer')) ?>';
const ajaxBaseUrl = '$ajaxBaseUrl';
return fetch(ajaxBaseUrl + eventName)
.then(response => {
if (!response.ok) console.warn('GET request failed');
return fetch(ajaxBaseUrl + eventName)
.then(response => {
if (!response.ok) console.warn('GET request failed');
return response.json()
})
.then(data => {
taggrsPush(data, false);
if (typeof callback === 'function') {
callback();
}
})
.catch(error => {
console.log(error);
})
;
}
</script>
})
.then(data => {
taggrsPush(data, false);
if (typeof callback === 'function') {
callback();
}
})
.catch(error => {
console.log(error);
});
}
JS;

echo /* @noEscape */ $secureRenderer->renderTag( 'script', [ 'type' => 'text/javascript' ], $helpersScript, false );
?>
4 changes: 2 additions & 2 deletions view/frontend/templates/noscript.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
/** @var \Taggrs\DataLayer\Block\NoScript $block */
/** @var \Magento\Framework\Escaper $escaper */

$url = $block->getGtmUrl(); ;
$gtmCode = $block->getGtmCode(); ;
$url = $block->getGtmUrl();
$gtmCode = $block->getGtmCode();
?>
<noscript>
<iframe src='https://<?= $escaper->escapeUrl($url); ?>/ns.html?id=<?= $escaper->escapeHtmlAttr($gtmCode) ?>'
Expand Down

0 comments on commit d09f5d3

Please sign in to comment.