Issue with AJAX navigation and window.history.pushState: Inability to go back using the "back" browser button

I have developed a small Javascript tool to enable partial content loading in a Plone site using AJAX (the global AjaxNav object contains all the necessary functions). I want the browser history (back and forward buttons) to work correctly, so I wrote the following function:

   var set_base_url = function (url) {
        var head=null,
            base=$('html base').first();
        if (base) {
            base.attr('href', url);
            log('set base[href] to '+url);
        } else {
            $(document).add('<base>').attr('href', url);
            log('created <base> and set href to '+url);
        }

   var history_and_title = function (url, title, data) {
        var stateObj = {
            cnt: increased_state_counter()
            };
        if (typeof data.uid !== 'undefined') {
            stateObj['uid'] = data.uid;
        }
        if (title) {
            if (AjaxNav.options.development_mode) {
                title = '(AJAX) ' + title;
            }
            document.title = title;
        }
        if (url) {
            set_base_url(url);
            window.history.pushState(stateObj, '', url);
        } else {
            window.history.pushState(stateObj, '');
        }
    };
    AjaxNav.history_and_title = history_and_title;

Despite calling this function without any visible errors (at least that I could see), clicking the "back" button in the browser or using the backspace key only changes the URL displayed, without reloading any content. While I am willing to accept full-page reloads for now, I believe it would be preferable to reload pages from the history via AJAX.

Can anyone spot an obvious error?

The code can be accessed at this link, although it is quite lengthy (~850 lines) because of the ambiguity of target URLs, which may specify an object or its view method. Therefore, I attempt up to two different URIs per hyperlink before processing (replacing contents, setting the title, event.preventDefault(), etc.), or returning true to load the entire page.

Answer №1

Don't forget to include the popstate event listener in your code. When using pushState, a new entry is added to the history collection, and by clicking the back button, a state is removed from the history just like with an array. The popstate event is attached to the window object and can access the state object set in pushState.

Providing information in the state object can guide actions on the current page, such as fetching necessary data for loading.

Experiment with the following snippet in your code to observe its output:

window.addEventListener('popstate', event => {
   const { state } = event;
   console.log(state);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of altering a property in input data within Vue.js

I have a component called Input.vue that displays a label and an input field of some type. Here is how it looks: <template> <div class="form-element"> <label :for="inputId" :class="['form-element-tit ...

Eliminate Dates from the Past - Jquery Datepicker

Currently, I am developing a booking system for my client. I have successfully disabled Sundays and Mondays (the days she is not open). However, I am now working on enhancing the functionality by blocking out past dates. Although I have written a function ...

Utilizing AJAX in ASP.net Web API 2 to send and receive JSON data efficiently

net Web API 2. I want to send a JSON string to one of my POST functions and receive JSON back. My AJAX: $("#btnPost").click(function (event) { var sqlQ = "SELECT TOP 50 LTRIM(RTRIM(REPLACE(OID, ' ', ''))) FROM vwPS_DAT WHERE OID != & ...

Customize Text Area's Font Based on Selected Option in Dropdown List

I'm currently working on an HTML file that includes a dropdown list and a text area. Here's the code snippet: <select id='ddlViewBy' name='ddlViewBy' onchange='applyfonttotextarea()'> <option value = ' ...

Fetching the Key-Value pairs from a HashMap in JavaScript/AngularJS

I am currently working with a HashMap in the Frontend that is being retrieved from the Backend: var myVar = {"24":{"amount":2,"minutes":30},"32":{"amount":3,"minutes":30}} Can anyone offer guidance on how to access both the keys and values in Javascript ...

Evaluating a string or object for compatibility

In my possession, I have a PHP array that has been encoded in JSON format: <script> var registeredEmails = <?php echo(json_encode($emails)); ?>; </script> To verify that this is functioning properly, I conduct the following test: conso ...

Combine similar JSON objects into arrays

I'm working with a dataset returned by a library, and it's structured like this: var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}] My goal is to group the "fName" values together and add '[]' to achieve the fo ...

Can you explain the rationale behind html and js?

I am experiencing an issue with my code. When I click on the "click" button, the color changes as expected but the console log is showing that the code is not working according to the logic I have implemented. Initially, the color is black which is correc ...

What is the best way to assign multiple events and handlers using the .on method?

I've been attempting to move a submenu using multiple handlers within the on method. My goal is to trigger the function panelON when the mouse enters one of the li elements, and execute the function panelOFF when the mouse leaves it. I have tried dif ...

Does the execution of node.js event handlers occur when the calling stack is clear?

My belief that code related to node.js events is asynchronous was challenged when I came across the following example: var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('foo', function () ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

Dealing with form errors - Using Node.js and Express Framework

Is there a way to handle errors that occur when dealing with null form inputs or unavailable cities from the weather api service? Sometimes, when an empty query or a misspelled city is inputted, the server returns errors and halts operation. app.get("/", ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

How to easily toggle all checkboxes within a Vue.js checkbox group

I'm struggling with manipulating an Array of checkboxes that are grouped into parent and child elements. I need to automatically check all child checkboxes when the parent is checked, uncheck them if the parent is unchecked, and update their states in ...

Discover the method to retrieve the chosen value from a list of radio buttons using AngularJS

After making an AJAX request and receiving JSON data, I have created a list of radio buttons with values from the response. Although I have successfully bound the values to the list, I am facing difficulty in retrieving the selected value. Below is a snipp ...

Arranging elements using the ng-repeat directive in AngularJS

My question pertains to an array I am working with: $scope.answers=["","","",""] This array contains several empty elements. <li ng-repeat="item in answers "><input type="text" ng-model="item"/></li> When running this code, an error i ...

Verifying that the data has been successfully saved using JavaScript

When a user submits a small chunk of data via AJAX using a standard update action and a remote form, the information is sent to the action as javascript. The response is then rendered in javascript utilizing format.js. def update @message = Message.wher ...

Establishing session management for tasks in Node.js

I'm currently developing a web application using Node JS and encountering an issue with the session store in req. For my sessions to work, I have set up my app.js like this: // Enable sessions app.use(session({ secret: '***********', ...

The search bar is equipped with Ajax code for real-time results. In the event that no data matches the search query

If the API call returns data, then the code works as expected. However, if it returns an empty response, it should display an error log but this is not currently happening. $.ajax({ type: "POST", url: "<?php echo base_url();?>homecontroller/catego ...