How to get recent viewed products in Shopify Store in any theme

<miniScript/>
5 min readSep 11, 2020
Shopify logo from Google search

Hi Developers 👋

This is my first blog post so my vocabulary might not be that impressive but you’ll definitely learn something after reading this.

I was working on client’s project and suddenly requirement came in for recent viewed products to show the users. So I start looking into at but there was nothing which I can use. There were some JavaScript plugins but I did not want to use any plugin or library, so I decided to write down all the code from scratch in core JavaScript.

If you want to get recent viewed products now you can do it with only single file no need to install any plugins or any library or any Shopify app.

This code will work with every Shopify theme you just need to include one file in snippets folder and include it on product template.

I leveraged the localStorage of browser to store the data and then use it view the products.

Let’s roll with code and make great customer experience.

Create a snippet recent-viewed-product-js.liquid for writing our code

Fetch the Current PDP data using liquid objects and store them into JS variable

<script type="text/javascript">
const pdpData = {
productTitle = "{{ product.title }}",
productImg = "{{ product.featured_image | img_url: 'small' }}",
productPrice = "{{ product.price | money | remove_first: '' }}",
productUrl = "{{ product.url }}"
}
console.log(pdpData)
</script>

Now if you do console.log(pdpData) the output should be something like this

Now let’s create some variables push data into Array’s. One thing we need to keep in mind is locaStorage store data in the forms of strings, so we need to convert our objects into Array to store.

First Block of Code

<script type="text/javascript">
// First Block
function setRecentlyViewedPdp() {
const pdpData = {
productTitle = "{{ product.title }}",
productImg = "{{ product.featured_image | img_url: 'small' }}",
productPrice = "{{ product.price | money | remove_first: '' }}",
productUrl = "{{ product.url }}"
};
console.log(pdpData)
// Init Empty Array to push data
const productArr = [];
// Create a couple of variables
let jsonResp,
jasonRespArr,
jsonRespArrStr;
// Set the number how many products you want to capture
const numberOfProduct = 4;
// Now push the pdpData into Array so that we can use it
productArr.push(pdpData);
// Get the product title from pdpData
const currPdpTitle = pdpData.productTitle;
// Now Convert current page data into Strings which we already pushed in Array const pdpDataString = JSON.stringify(productArr);// Set the variable for localStorage
const localData = localStorage.getItem('recently_viewed');

we have done the following items so far
1. Get data from Product page and push that into Array.
2. Converted rhe Array data into strings for further use.
3. Set the variable for our local storage.

Now we need to Store this data into localStorage for 4 consective page.
PS: you need to follow up from above code this is next block of code

Second Block of Code

// Second Block
// first we need to check data if data is not there then store right // away
if (localData == null) {
localStorage.setItem('recently_viewed', pdpDataString);
}
// If data is there then we need to check couple of other conditions
else if ( localData == null ) {
// Create Variable for oldData or Previous page
const oldPdpData = localStorage.getItem('recently_viewedPDP');
// Count the amount of data stored in strings so that we can remove // old products from the stack
const countPdpData = (oldPdpData.match(/productTitle/g) || []).length;
// we also need to check if user is not visiting page again
cont reVisitPdp = oldPdpData.includes(currPdpTitle);
// Get old data, merged it with new data and store merged data
if (countPdpData < numberOfProduct && reVisitPdp == false) {
jsonResp = JSON.parse(oldPdpData);
jsonRespArr = jsonResp.concat(productArr);
jsonRespArrStr = JSON.stringify(jsonRespArr);
localStorage.setItem('recently_viewedPDP', jsonRespArrStr);
}
// If User visited more the 4 pages delete first page data
else if (countPdpData >= numberOfProduct && reVisitPdp == false) {
jsonResp = JSON.parse(oldPdpData);
jsonResp.shift();
jsonRespArr = jsonResp.concat(productArr);
jsonRespArr = JSON.stringify(jsonRespArr);
localStorage.setItem('recently_viewedPDP', jsonRespArr);
}
}
}
// Now we write all our function and it's time to execute it
setRecentlyViewedPdp();
// Set Variable for Local Storage Data
const localViewed = localStorage.recently_viewedPDP;
// console.log to verify the data
console.log(localViewed);

The Data stored in localStorage is in string form so it would be look like this

Console.log(localViewed);

So we got the data for last visited products now we need to write a function to inject data into product page.

Create a empty <div> which we can use to inject our data

Third and Final block of Code

<div class="js-recentPdpBlock o-flex">
<!-- Recent Viewed Products would appear here -->
</div>

Let’s write the function() and inject data on product page

// Third Block
function getRecentPdp (){
// First let's convert localStorage data into object again
const pdpData = JSON.parse(localStorage.getItem('recently_viewedPDP'));
// Create a empty Array
const recentViewHtml = []
// Loop through all the data and inject into HTML using ES6
pdpData.forEach(function(item){
recentViewHtml.push(`
<div class="c-product">
<div class="c-product__img">
<img src='${item.productImg}'/>
</div>
<h3 class="c-product__title">
<a class="c-product__url" href="${item.productUrl}">
${item.productTitle}
</a>
</h3>
<p class="c-productPrice">${item.productPrice}</p>
</div>
`)
})
// Now consolidate the data
const recentBlock = `${recentViewHtml.join('')}`
// console.log() to check data is correct
console.log(recentBlock);
// Inject into PDP page const contentBlock = document.getElementsByClassName('js- recentPdpBlock'); // Push the data
contentBlock[i].innerHTML = recentBlock;
}// Execute this function on DOM content load document.addEventListener("DOMContentLoaded", function(event) {
getRecentPdp();
});
</script>
// Done ✅
// Happy Coding

So we’re done with very cool feature on our Shopify Store.

If you like it do share and like it.

Happy Coding ..

Created with Love ❤️
@miniScript

Technical lead at Anatta

Anatta.io

--

--

<miniScript/>

Coder, Lifestyle, Troubleshooter, Entrepreneur, Horse rider, GT Avalanche Rider