cancel
Showing results for 
Search instead for 
Did you mean: 

Is it possible to add a JS before the </body> tag for the products page only?

Is it possible to add a JS before the </body> tag for the products page only?

Hi to all !

Hope this is the right topic for this forum branch. I am still new to Magento 2.4.1. I would like to add a JS code right before the closing body tag for the products page. But I don't know if it is possible and where that would be.

Any help or tips on where to start or what to look for, is greatly appreciated !

Thanks

m.

1 REPLY 1

Re: Is it possible to add a JS before the </body> tag for the products page only?

Please implement the below code:

In the catalog_product_view.xml file:

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Text" name="TestScript">
            <arguments>
                <argument name="text" xsi:type="string"><![CDATA[<script type="text/javascript" src="//www.anyDomain.com/test-script.js"></script>]]></argument>
            </arguments>
        </block>
    </referenceContainer>
</body>
</page>
OR
You can implement the below indirect method too.
In the catalog_product_view.xml file:
<referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Template" template="Namespace_ModuleName::beforeBody.phtml" name="before_body_js"/>
</referenceContainer>
Add script you want to add in beforeBody.phtml
in beforeBody.phtml add script you want to add like below :
<script src="js path"/>
OR
<script>
        require(
            [
                'jquery'
            ],
            function ($){ .... }
            );
</script>
Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.