Navigating pages with AJAX and restoring browser state

Exploring the world of AJAX-based navigation on a Rails website, with some basic jQuery hooks written in Coffeescript:

$(document).on 'click', 'a.ajax_nav', (e) ->
  window.history.pushState(null, "page title", this.href)

$(window).on 'popstate', (e) ->
  $.getScript(document.location)

Here's the equivalent Javascript version:

$(document).on('click', 'a.ajax_nav', function(e) {
  return window.history.pushState(null, "page title", this.href);
});
$(window).on('popstate', function(e) {
  return $.getScript(document.location);
});

The navigation is smooth, allowing me to use back/forward buttons and refresh the page. However, I encountered an issue when navigating using AJAX, closing the browser, and reopening it with the "restore tabs" option. The page displayed script code instead of executing it, possibly due to the cached server response being the script itself.

So my question is, can we manipulate the browser cache to force a reload? For example, setting response headers to no-cache for JS format requests. Would this trigger a reload and default to HTML rendering?

Appreciate any insights!

Answer №1

To address the issue, I made a modification to my main application controller (application_controller.rb) by incorporating the following code:

class ApplicationController < ActionController::Base
  .
  .
  before_filter :set_cache_for_js
  .
  .
  protected

    def set_cache_for_js
      set_cache_buster if request.format == 'text/javascript' # potential room for improvement here
    end

    def set_cache_buster
      response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
      response.headers["Pragma"] = "no-cache"
      response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
    end
.
.
end

This adjustment ensures that the set_cache_for_js filter is employed prior to every action across the entire application. In instances where javascript is the requested format, the headers are adjusted to invalidate the cache, preventing the browser from storing the javascript response and necessitating a page reload based on the URL to display the document correctly.

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

Merge two arrays together and arrange them in ascending order based on the dateTime field

I have combined two sorted arrays into a new listC. listA = [ {id:"1234435", name:"apple", dateTime_ISO:"2019-01-15 17:27:30"}, {id:"1234435", name:"orange", dateTime_ISO:"2019-01-15 10:25:30"}, {id:"1234435", name:"banana", dateTime_ISO:"2019-01-15 ...

An error has occurred in NodeJS: Value undefined is out of the acceptable range for an unspecified property in the options

I am currently leveraging worker_threads in nodejs to handle the task of reading multiple files and processing the rows for subsequent insertion into a database (using oracle-db). The volume of data I deal with is substantial, typically exceeding one mill ...

What is the best way to sort through custom components within children in Solid JS?

I have been working on developing a scene switcher for my personal application, and I thought of creating a custom component called SceneSwitcher. Inside this component, I plan to add various scenes that can be rendered. Here's an example: <SceneSw ...

AngularJS Pagination: Organizing Content Efficiently

Utilizing Bootstrap's Pagination directive to implement pagination in a table. Interestingly, when manually adding data to $scope.transactions (referencing the commented out code in the controller), the pagination functions flawlessly. However, attem ...

What is the best way to modify the inline style width of a table td from pixels to percentage in order to make it

<table> <tr style="height:15pt;"> <td style="width:229pt;border-style:solid;border-width:0pt;padding:3pt 9pt 3pt 0pt;" valign="bottom" bgcolor="#c0c0c0"><p style="font-family:Times New Roman, serif;font-size:10pt;font-style:norm ...

Tips for organizing an array into three separate objects based on specific criteria

I have taken a word and split it into an array. Now, I am trying to divide that array into 3 separate objects like this: Input: var input = "7RD FLOOR, PAVE AVENUE BUILDING, DUNG STREET, 48 JUNG-GU, SEOUL 100-203" Desired Output: let addresses = { ad ...

Creating a robust system for resetting passwords using the powerful combination of Django Rest Framework, Serializers, and Vue.js

I am currently in the process of implementing a reset password feature, but I am struggling to find comprehensive tutorials on how to do so using DRF and Vue.js. My approach involves utilizing serializers for data passing without incorporating HTML views. ...

Is there a way to send the value of a jQuery variable to be retrieved by a PHP $_POST method?

I have successfully managed to gather all the values from a multi-select form into a single delimited variable. However, I am struggling to pass this 'output' value to my PHP script utilizing the $_POST array. How can I ensure that the 'outp ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...

JSDoc encounters issues when processing *.js files that are produced from *.ts files

I am currently working on creating documentation for a straightforward typescript class: export class Address { /** * @param street { string } - excluding building number * @param city { string } - abbreviations like "LA" are acceptable ...

Issue with shadows on imported OBJ objects in Three.js when material is applied

After importing an obj using this load function: // triggered when the resource is loaded function ( obj ) { // For any meshes in the model, add our material. obj.traverse( function ( element ) { if ( element instance ...

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Using Firefox to cache Ajax calls after navigating back in the browsing history

Currently, I am utilizing an ajax call to invoke a php script that waits for 40 seconds using sleep and then generates the output RELOAD. Subsequently, in JavaScript, the generated output is validated to be RELOAD, following which the call commences again. ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

How can I detect a click event in Angular using Typescript?

I am looking to transform the provided jquery scripts into typescript code. Jquery $(".room").click({ console.log("clicked"); }); TypeScript import { Component } from '@angular/core'; declare var $: any; export class AppComponent { } ...

Preview functionality is disabled in the iOS share extension

Currently, I'm developing a share extension for Safari on iOS. Our approach involves utilizing the default UI provided by iOS and extending the SLComposeServiceViewController class. In addition to this, I have incorporated a JavaScript function to ext ...

Tips for creating a safe ajax request with asp.net

As I delve into the world of ajax, I find myself faced with a situation in which I am utilizing Ajax on my website to pass parameters and retrieve records from a database based on said parameters. However, upon inspecting the network tab in the browser&ap ...