Changing the location.hash parameter prior to the page loading

Imagine a scenario where a page contains only the following script:

<script type="text/javascript">
  window.location.hash = 'testing';
  window.history.back();
</script>

When you navigate to google.com and then load this page, you'll notice the hash changing in the address bar, but the page immediately redirects back to Google. Ideally, the #testing hash should just be removed.


If I introduce a slight delay using a setTimeout function, everything works as intended:

<script type="text/javascript">
  setTimeout(function () {
    window.location.hash = 'testing';
    window.history.back();
  }, 1000);
</script>

In this case, the address bar momentarily displays the #testing hash before it disappears.


This indicates that modifications to the location.hash are reflected in the history api with some latency. There seems to be an event triggering this behavior change.

After reviewing the available events on mdn, I came across:

pageshow: The pageshow event occurs when a session history entry is being accessed. (This covers back/forward navigation and the initial page showing after the onload event.)
load: The load event is triggered once a resource and its dependencies have finished loading.

However, neither of these events resolves the issue. I attempted:

<script type="text/javascript">
  window.addEventListener('pageshow', function () {
    window.location.hash = 'testing';
    window.history.back();
  }, false);
</script>

and repeated the process with the load event. The result remains the same - the address bar flickers with the #testing hash before reverting to the previous page.


How can I determine if it's safe to modify the location.hash successfully?

Answer №1

It appears that the load event is heading in the right direction, but with a small twist. The history api detects the change one tick later than the load event.

Here is an example of the issue:

<script type="text/javascript">
  window.addEventListener('load', function () {
    window.location.hash = 'testing';
    window.history.back();
  }, false);
</script>

However, this code successfully removes the hash:

<script type="text/javascript">
  window.addEventListener('load', function () {
    setTimeout(function () {
      window.location.hash = 'testing';
      window.history.back();
    }, 1);
  }, false);
</script>

I'm unsure of the reason behind this behavior, and I haven't been able to find any specifications that support this scenario. This discovery was made through trial and error.

Update as of 2023: This behavior still persists in Chrome v111 and Safari v16.3, but it does not occur in Firefox v111.

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

Is it better to manually input a list of select options in the user interface or retrieve them dynamically from the database in case of future changes?

Imagine designing a user interface that allows users to choose their favorite Pokemon from options like Bulbasaur, Squirtle, and Charmander. Within the database, there is a lookup table containing all possible choices: pokemon --- id name 1 Bulbasaur 2 ...

Switching images using jQuery

Issue I'm feeling overwhelmed by the abundance of JavaScript code hints and finding it difficult to determine where to begin. Any assistance would be greatly appreciated. Essentially, I have a primary full-screen background image set in the CSS on t ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

Altering webpage content through the use of Ajax

I need a solution for dynamically updating web page content using JavaScript AJAX. One idea I had was to store different div layouts in separate files, like so: BasicDiv.div: <div> <p>Some Text</p> <button> A Button </ ...

Acquire the key name of an object during iteration in Jade

const information = { attribute1: 'value1', attribute2: 'value2', attribute3: 'value3' }; for each value, key in information li= value.keyname?? The desired result should be: <li>attribute1</li> <li ...

React Native - Implementing a dynamic form that adapts based on the answer given by its parent

My JavaScript Object has a simple state structure as follows: pertanyaan: [{ label: "label1", type: 'dropdown', key: 'keyFoo1', option: [{ value: "foo1" }, { value: "foo2", additional ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

Arrangement of components within an entity

I have an instance (let's refer to it as myObject) that is structured like this (when you log it to the console): >Object {info1: Object, info2: Object, info3: Object, info4: Object,…} >info1: Object >info2: Object Id: 53 ...

I am experiencing an issue with FreeTextBox where a Javascript error is causing problems with the Post

I encountered an issue on my webpage where I have three FreeTextBox controls. Everything was working fine until I added a DropDownList control that needed to PostBack to the server. Surprisingly, the OnSelectedIndexChanged event did not trigger when using ...

Maximizing efficiency in processing multiple requests simultaneously using ajaxSetup's data

I need to enhance an existing ajax request within our CMS by adding additional data. Specifically, I am working with a media library that loads image data (json), and I want to incorporate more images from an external source. var promise_waiting = []; jQu ...

Encountered an unhandled promise rejection: TypeError - The Form is undefined in Angular 6 error

Whenever I attempt to call one .ts file from another using .Form, I encounter the following error: Uncaught (in promise): TypeError: this.Form is undefined The file that contains the error has imported the .ts file which I intend to pass values to. ...

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

"Encountering a 404 error when submitting a contact form in Angular JS

Looking to set up a contact form for sending emails with messages. Currently diving into Angular Express Node Check out the controller code below: 'use strict'; /** * @ngdoc function * @name exampleApp.controller:ContactUsCtrl * @descripti ...

Reasons Why Optional Chaining is Not Utilized in Transpiling a Node.js + TypeScript Application with Babel

Currently, I am delving into Babel in order to gain a deeper understanding of its functionality. To facilitate this process, I have developed a basic API using Node.js and TypeScript. Upon transpiling the code and initiating the server, everything operates ...

Can you explain what JSX is, its purpose, and the benefits of using it?

As I delve into the world of React, I can't escape the constant mention of JSX. Despite my efforts to grasp it by watching tutorials, the concept still eludes me. Even after consulting the documentation, my mind remains in a state of confusion. To m ...

Tips for creating a gradual fade-out effect on a bootstrap modal window

One issue I'm facing is with my modal dialog (#busyIndicator). It simply displays a message that reads "Please Wait". Sometimes, the operation it's tied to completes so quickly that the visual transition between showing and hiding the dialog beco ...

Steps for invoking a Node.js function from a distinct JavaScript function on the front end

I am currently working on a project that involves a node js backend (app.js) connected to an HTML, CSS, and Javascript frontend (script.js). Within my HTML file, I have a form that allows users to upload an image, triggering a function in script.js to han ...

Node.js: Changing binary information into a readable string

I'm faced with a challenge - the code I wrote seems to be returning data in binary format. How can I convert this into a string? fs.readFile('C:/test.prn', function (err, data) { bufferString = data.toString(); bufferStringSplit = buff ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...