website logo
Product FeedCommunity Forum
API Docs
Template JS
Headless SDK
Navigate through spaces
API Docs
Template JS
Headless SDK
⌘K
Introduction
Getting Started
Quickstart : Smart Search
Quickstart : Smart Category Merchandising
Quickstart : Smart Recommendations
Apps/Plug-ins
Guide
Structure
Configuration
JS Library
Versioning
Template Reference
Build UI
Custom Overrides
Recommendations Webhooks
Styling CSS
Analytics/Tracking
How To
Add Filters To URL
Add Pagination To URL
Add-To-Cart Function
Customer Groups
Infinite Scroll Results
Magento B2B MSI
Ratings / Reviews
SortBy Options
Docs powered by archbee 
3min

Add Pagination To URL



There are times when it is beneficial to have the users selected pagination captured and stored as part of the URL.

For Example :

  • Allow for consistent tracking of the selected page of results.
  • Reusable 'landing page' links
  • SEO

To accomplish this we will add in a custom override module that will:

  1. Intercept the outgoing query
  2. Analyze the existing URL string
  3. Update the localstorage of selected page value
  4. Apply the page offset to the outgoing query
  5. Update the existing URL string

See : Custom Overrides for details on preparing for Klevu JS overriding

Template JS Override

Add the supporting module addPaginationToURL and apply it to the landing page override.

Note : the same addPaginationToURL module can be used on Category pages by applying the override to the catnav scope as well.

Full Example

JavaScript
|
<script type="text/javascript">

// Defer initialization (powerUp) of the Klevu components
    klevu({
        powerUp: {
            landing: false
        }
    });


// OVERRIDE :  LANDING PAGE
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {

            // Apply the page value supplied in the current URL string
            klevu.search.landing.getScope().chains.request.control.addAfter("initRequest", {
                name: "selectPageNumberFromURL",
                fire: function (data, scope) {
                    klevu.search.modules.addPaginationToURL.base.getAndUpdatePagination(data, scope);
                }
            });
            
            // Add selected page value to the URL string
            klevu.search.landing.getScope().chains.template.events.add({
                name: "attachURLUpdateOnPaginationSelect",
                fire: function (data, scope) {
                    klevu.search.modules.addPaginationToURL.base.setPagination(data, scope);
                }
            });

            //  power up
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });


// addPaginationToURL module
(function(klevu) {
    klevu.extend(true, klevu.search.modules, {
        addPaginationToURL: {
            base: {
                setPagination: function(data, scope, queryId) {
                    var hasPaginationEnabled = klevu.getSetting(klevu, "settings.theme.modules.pagination.searchResultsPage.enable");
                    if (hasPaginationEnabled === true) {
                        var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                        if (queryId && queryId.length) {
                            activeQueryId = queryId;
                        }
                        var paginationQueryParam = activeQueryId + "PgNo";
                        var activeQueryMeta = klevu.getObjectPath(data, "template.query." + activeQueryId + ".meta");
                        var paginationValuesQueryParam = 0;
                        if (activeQueryMeta) {
                            var productListLimit = activeQueryMeta.noOfResults;
                            paginationValuesQueryParam = Math.ceil(activeQueryMeta.offset / productListLimit) + 1;
                        }
                        var searchPath = window.location.search;
                        var updatedPath = klevu.dom.helpers.updateQueryStringParameter(searchPath, paginationQueryParam, paginationValuesQueryParam);
                        if (paginationValuesQueryParam === 0) {
                            updatedPath = updatedPath.replace("&" + paginationQueryParam + "=", "");
                        }
                        if ('undefined' !== typeof window.history && 'undefined' !== typeof window.history.replaceState) {
                            window.history.replaceState({}, "", updatedPath);
                        } else {
                            console.log("This browser does not have the support of window.history or window.history.replaceState");
                        }
                    }
                },
                getAndUpdatePagination: function(data, scope, queryId) {
                    var hasAlreadyTriggered = klevu.getObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered");
                    if (hasAlreadyTriggered === true) {
                        return;
                    }
                    var matchedQueryParamId = ""
                      , matchedQueryParamValue = "";
                    var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                    if (recordQueries && recordQueries.length) {
                        klevu.each(recordQueries, function(key, query) {
                            if (query.id) {
                                var paginationFromURL = klevu.dom.helpers.getQueryStringValue(query.id + "PgNo");
                                if (paginationFromURL && paginationFromURL.length) {
                                    matchedQueryParamId = query.id;
                                    matchedQueryParamValue = paginationFromURL;
                                }
                            }
                        })
                    }
                    klevu.setObjectPath(scope.kScope, "element.kScope.getAndUpdatePaginationTriggered", true);
                    var activeQueryId = klevu.getObjectPath(data, "context.activeQueryId");
                    if (queryId && queryId.length) {
                        activeQueryId = queryId;
                    } else if (matchedQueryParamId.length && matchedQueryParamValue.length) {
                        activeQueryId = matchedQueryParamId;
                        var storage = klevu.getSetting(scope.kScope.settings, "settings.storage");
                        if (storage.tabs) {
                            storage.tabs.setStorage("local");
                            storage.tabs.mergeFromGlobal();
                            storage.tabs.addElement("active", activeQueryId);
                            storage.tabs.mergeToGlobal();
                        }
                    }
                    var paginationQueryParam = activeQueryId + "PgNo";
                    var paginationFromURL = klevu.dom.helpers.getQueryStringValue(paginationQueryParam);
                    paginationFromURL = Number(paginationFromURL);
                    if (paginationFromURL && paginationFromURL > 1) {
                        var recordQueries = klevu.getObjectPath(data, "request.current.recordQueries");
                        if (recordQueries.length) {
                            klevu.each(recordQueries, function(key, recordQuery) {
                                if (recordQuery.id === activeQueryId) {
                                    var limit = klevu.getObjectPath(recordQuery, "settings.limit");
                                    limit = Number(limit);
                                    if (limit > 0) {
                                        var expectedOffset = (paginationFromURL - 1) * limit;
                                        klevu.setObjectPath(data, "localOverrides.query." + activeQueryId + ".settings.offset", expectedOffset);
                                    }
                                }
                            });
                        }
                    }
                }
            },
            build: true
        }
    });
}
)(klevu);

</script>




Updated 03 Mar 2023
Did this page help you?
Yes
No
UP NEXT
Add-To-Cart Function
Docs powered by archbee 
TABLE OF CONTENTS
Template JS Override