Magento 2.2.4 Issue – Fix Quotation Mark Breaking Product Pages

productproduct-page

I have just installed Magento 2.2.4 to try out and have so far noticed a few issues in my first half hour. Was wondering if this is just my custom installation or is happening for anyone else.

The product images alt attribute seems to be loaded asynchronously and appended under the product image. The product page seems to stop processing javascript just before this however breaking the page. This seems to fail if a quotation mark exists in the product name (e.g. 12" Ruler (30cm)) throwing the below error:

Uncaught SyntaxError: Unexpected token ( in JSON at position 129
at JSON.parse (<anonymous>)
at getData (main.js:58)
at Array.map (<anonymous>)
at HTMLDocument.apply (main.js:74)
at fire (jquery.js:3232)
at Object.add [as done] (jquery.js:3291)
at jQuery.fn.init.jQuery.fn.ready (jquery.js:3542)
at jQuery.fn.init (jquery.js:2967)
at new jQuery.fn.init (jquery-migrate.js:225)
at jQuery (jquery.js:75)

Switching the product name fixed the immediate issue however there are many items with quotation marks to change and want to solve this without changing product names.

It seems that quotations in product names are not being escaped for the breadcrumbs as logging the object just before the error shows below:

{
"breadcrumbs": {
    "categoryUrlSuffix": ".html",
    "useCategoryPathInUrl": 0,
    "product": "12" Ruler (30cm)"
}
}

Best Answer

For now I have overridden the file for the breadcrumbs within my own theme.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/** @var \Magento\Theme\Block\Html\Breadcrumbs $block */
/** @var \Magento\Catalog\ViewModel\Product\Breadcrumbs $viewModel */
$viewModel = $block->getData('viewModel');
?>
<div class="breadcrumbs" data-mage-init='{
    "breadcrumbs": {
        "categoryUrlSuffix": "<?= $block->escapeHtml($viewModel->getCategoryUrlSuffix()); ?>",
        "useCategoryPathInUrl": <?= (int)$viewModel->isCategoryUsedInProductUrl(); ?>,
        "product": "<?= htmlspecialchars($block->escapeHtml($viewModel->getProductName())); ?>"
    }
}'>
</div>

Replace line 14 adding the htmlspecialchars function to format quotations within the product name on breadcrumbs json as &quot:

Original:

"product": "<?= $block->escapeHtml($viewModel->getProductName()); ?>"

vendor/magento/module-catalog/view/frontend/templates/product/breadcrumbs.phtml

Replaced with:

"product": "<?= htmlspecialchars($block->escapeHtml($viewModel->getProductName())); ?>"

app/design/frontend/ThemeVendor/ThemeName/Magento_Catalog/templates/product/breadcrumbs.phtml

There is probably a more elegant way of fixing this however this will do for now.

Related Topic