Magento - add inline javascript to product page via xml code update layout

Hi, I want to use the Google Analytics AB-Testing engine. Therefore, I have to add a javascript snippet to individual product pages.

I would like to add it to the description or a short description. It works, but not enough, because the script does a redirection, which means the page loads halfway and then redirects.

Google says that I should add a script to the head-tag. Is it possible to insert a script as a "custom layout update" here: enter image description here

I could imagine something like

<default translate="label" module="page"> <label>All Pages</label> <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml"> <block type="page/html_head" name="head" as="head"> <action method="addJs"><script>alert('hello')</script></action> </block> </block> </default> 
+6
source share
2 answers

This is a cleaner for loading javascript from a file. You do not need all these blocks, but you can do it like this:

 <default translate="label" module="page"> <reference name="head"> <action method="addJs"><script>path/to/script.js</script></action> </reference> </default> 

The path is the relative path from the js folder to the root of magenta.

To add javascript to xml directly (which I do not recommend), you can use CDATA, for example:

 <reference name="head"> <block type="core/text" name="your.block.name"> <action method="setText"> <text><![CDATA[<script type="text/javascript">alert('hello');</script>]]></text> </action> </block> </reference> 
+21
source

My solution was to expand the head unit:

 <?php class Company_Modulename_Block_Html_Head extends Mage_Page_Block_Html_Head { public function addInlineJs($name) { $this->addItem('inlinejs', $name); return $this; } public function getCssJsHtml() { $html = parent::getCssJsHtml(); foreach ($this->_data['items'] as $item) { if($item['type']=='inlinejs') { $html .= sprintf('<script type="text/javascript">%s</script>' . "\n", $item['name']); } } return $html; } } 

now i can use it that way

 <reference name="head"> <action method="addInlineJs"><script>alert('cool');</script></action> </reference> 
+1
source

Source: https://habr.com/ru/post/969942/


All Articles