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

miniscript
Shopify Partner
28 1 10

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

Replies 9 (9)

Smeelah
Navigator
333 1 91

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:( 

 

miniscript
Shopify Partner
28 1 10

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

Smeelah
Navigator
333 1 91

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
Shopify Partner
28 1 10

Yeah you need shopify Expert for that.

NagoyaDev
Excursionist
26 1 1

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!

 

LJK
Visitor
1 0 1

Hey @NagoyaDev 

You may have worked it out by now,  but I was working on an implementation of this(thanks Miniscript!) and experienced the same as you.😄😄

I found that I received an invalid shorthand property initializer error for the recent-viewed-product-js.liquid initially.

In the pdpData object, changing the assignment of each property of the object from = to the colon (:) would work. JS would expect the colon for assigning values to properties of objects.

Hope that helps, seemed to resolve things here!

Luke

 

NagoyaDev
Excursionist
26 1 1

Thanks for the help! 

 

I ended up using a bit of code developed by a previous Shopify developer and modifying it to my needs! 

Xceeder
Shopify Partner
1 0 1

I've fix some errors, But thank you for this 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 }}"
        };

        // Init Empty Array to push data
        const productArr = [];
        // Create a couple of variables 
        let jsonResp,
            jsonRespArr, 
            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_viewed');
            // 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 
            const 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_viewed', 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_viewed', 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_viewed;
    // console.log to verify the data 


    // Third Block
    function getRecentPdp (){

        // First let's convert localStorage data into object again
        const pdpData = JSON.parse(localStorage.getItem('recently_viewed'));
        console.log(pdpData)
        // 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.querySelectorAll('.js-recentPdpBlock');
        // Push the data
        contentBlock.forEach(element =>{
            element.innerHTML = recentBlock;
        })
       
    }
    // Execute this function on DOM content load 

    getRecentPdp();



LuizFelipeRolim
Tourist
9 0 0

Hello @Xceeder .

I am building a landing page at the page product. My intension is to have 5 products, each one with it's own landing page. I will not use the main page, just the landing pages.

Thats why, when someone click at the logo (header) or some "back to store" button, I need them to go to the last "product page" they visit, not just the "last page".

 

So, based on your code, witch "href" do I need to use to insert on the logo and the buttons to lead the visitors to the previous product page they visited?