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

miniscript
Excursionist
21 1 8

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

 

 

 

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

 

 

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 

 

 

// 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);

 

 

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

Technical Lead at Anatta

Smeelah
Trailblazer
262 1 62

I love a single file with no app etc. I would love to see a demo of this. I would also love to try it out but I am not a developer and so unfortunately I do not understand how to fetch and store and convert object into array:( 

 

0 Likes
miniscript
Excursionist
21 1 8

Hi - This  feature is implemented on this store - https://cariuma.com/products/oca-low-off-white-canvas-sneaker-men - 
You can check it out. 

0 Likes
Smeelah
Trailblazer
262 1 62

Thank you. It looks great. I love how it's integrated with 'you might like' section. I do hope that a Shopify expert will take you up on this challenge. I would love to know how to implement!

miniscript
Excursionist
21 1 8

Yeah you need shopify Expert for that.

NagoyaDev
Tourist
7 0 0

You wouldn't have a repo showing how you implemented this into your code into your project, do you?

 

I tried following what you put down but couldn't get anything to show?

 

I created a snippet file with the same name and then just copied your code into it like so:

 

<script>


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

// 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');



// 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);



// 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>


<div class="js-recentPdpBlock o-flex">

    
</div>

I then added the snippet to my product page. I see the js-recentPdpBlock div appear on my page but I don't see a cookie appear in the application tab of chrome tools when I visit the product pages.

Is this the correct way to put everything in or did I miss something?

 

If you could help me understand, I would really appreciate it!

 

0 Likes