0
votes

This is a code on the product page x and the product id is 56

    sessionStorage.setItem("prodid", "%prodcode%");

I can call this product code on the y page using the code below

     alert(sessionStorage.getItem("prodid"));

Comment: I will get a alert of 56

But what i want is to get the value of the product code in view source so that i can pass it to third parties like Google analytics.

For example:

_gaq.push(['_addTrans', '56', // product code 'Acme Clothing', // affiliation or store name '11.99', // total - required '1.29', // tax '5', // shipping 'San Jose', // city 'California', // state or province 'USA' // country ]);

The above analytics code is just an example.

1
There's no way to do that. You could instead use the console: console.log(sessionStorage.getItem("prodid")); (F12 Developer Tools, Firebug, Chrome Console, etc.)... - Cᴏʀʏ
If you want the value in the HTML just output %prodcode% again. - nullability
No, that doesn't works if i want to call the product code on an another page - sivi
You're probably thinking of something like echo which is found in some languages. Javascript has document.write(), but I would advise creating a node that you can append it to as a text node instead. - Joseph Marikle
Yes, you are correct but document.write actually writes it to frontend. But i wanted it get it displayed on the view source... - sivi

1 Answers

0
votes

I think you have two options here, depending on what you mean by "view source". If right-clicking and selecting "View source" is what you mean, then doing a document.write is your best option:

document.write('<!-- prodid: ' + sessionStorage.getItem('prodid') + ' -->');

If you have the ability to view the source in other ways, like using Firebug, Chrome developer tools, or the IE developer tools, then you can simply output the value in a hidden form field. This will not appear on the UI:

var prodIdElement = document.createElement('input');
prodIdElement.id = 'prodid';  // in case you want to target it in the DOM
prodIdElement.type = 'hidden';
prodIdElement.value = sessionStorage.getItem('prodid');

document.body.appendChild(prodIdElement);

You can then view the page's "rendered" source in the dev tool(s) of your choice, and you should see the newly added element at the bottom of the body.