Executing a JavaScript function by utilizing the # symbol in the URL: Tips and Tricks

It all began with a function called loadround that changed the innerHTML of an iframe. The links within the iframe would then change the page when clicked, but hitting the back button made the loadround page vanish. I pondered over this issue multiple times without success, so I experimented with some code.

<a href="javascript:void(loadround('parameter1','parameter2'))">loadround</a>

Then, I tested out the following code:

function loadround(a,b){
window.location.hash = "#loadround('"+a+"','"+b+"')";
var code = "<(h2)>"+a+"</(h2)><(h2)>"+b+"</(h2)>"
   var iFrame =  document.getElementById('iframe');
   var iFrameBody;
   iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0]
  iFrameBody.innerHTML = code;
 }

(note: the brackets in the h2 tags are purposeful) Next, I attempted to reload the function using an onload function, but for testing purposes, I used a simple href like this:

function check(){
var func = location.hash.replace(/#/, '')
void(func);
}
<a href="javascript:check()">check</a>  

Unfortunately, the check code did not work as expected, and I believe there must be a simpler way to achieve this. I also tried changing the src of the iframe instead of altering the innerhtml, but encountered the same issue. Appreciate any help in advance!

Answer №1

Recently, modern browsers have begun supporting the event window.onhashchange

In the interim, you can implement the workaround suggested by Lekensteyn or explore other potential solutions here: JavaScript/jQuery - onhashchange event workaround

Answer №2

There seems to be a misunderstanding regarding the void function, which is used to ensure that the return value is undefined. This prevents the browser from navigating away when the function is placed within a link. You can test this by entering the following addresses directly into your browser:

javascript:1        // Browser will display "1" as the return value is 1
javascript:void(1)  // Browser won't navigate away as the return value is undefined

It's important to note that executing the hash part as Javascript poses a security risk for XSS attacks if not properly validated. It is recommended to monitor changes in the hash part and take appropriate action.

For instance, you can continuously check for modifications in the hash part every 50 milliseconds and display it inside an element with ID targetElement. If the hash part is invalid, replace it with home.

var oldHash = '';
function watchHash(){
    var newHash = location.hash.substr(1);
    if (oldHash != newHash) {
        var validated = newHash.match(/^(\w+)$/);
        if (validated) {
            var code = "<h1>" + validated[1] + "</h1>";
            var element = document.getElementById("targetElement");
            element.innerHTML = code;
        } else {
            location.replace("#home");
        }
        oldHash = newHash;
    }
}
setInterval(watchHash, 50);

Sample HTML code:

<a href="#home">Home</a>
<a href="#about">About Me</a>
<a href="#contact">Contact</a>
<div id="targetElement">
    <!-- Inserted HTML content will appear here -->
</div>

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

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

What's the CSS equivalent of Java's window.pack() method?

I'm relatively new to css and I'm attempting to create a border around a <div>. My goal is for the border to be limited to the size of the elements inside the div and adjust dynamically in proportion to any new objects that may appear or di ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

JavaScript animation is not functioning as expected

I created a div with the id of "cen" and gave it a height and width of 50px. $(document).ready(function() { $("#cen").animate({ height: 500px, width: "500px", }, 5000, function() { // Animation complete. }); }); Unfort ...

Ways to maintain a pointer to a RequireJS module?

Understanding the inner workings of RequireJS has been a bit challenging for me, as the official website doesn't provide clear explanations on fundamental concepts like how to utilize the 'require' and 'define' methods. Currently, ...

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

Disabling data-scroll-speed on mobile devices

As a beginner in JavaScript/jQuery, I am working on incorporating code that changes the scrolling speed of specific elements on my webpage. However, I am struggling to disable this code for smaller screen widths. Here is the code snippet I have so far: &l ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

Steps to Display a JavaScript Function Two Times on a Single Page

Hey there! I'm currently working on a project where I need to display the output of my function in two separate divs. However, when I try to simply output the same ID, it messes up the whole code and the output becomes null. Here's the code snipp ...

Stable header that jumps to the top when scrolled

I have implemented the JavaScript code below to set the header to a fixed position when it reaches the top of the page so that it remains visible while the user scrolls. Everything appears to be functional, but the header movement is abrupt and not smooth. ...

ReactJS - Travel Booking Platform with Advanced Date and Price Filtering

Currently, I am in the process of developing a project — a website similar to AirBnB or Booking.com for booking rooms. The backend is built on Java Spring, while the frontend uses ReactJs. Although most of the code runs smoothly, I'm encountering s ...

What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved. Here ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

How to extract user data from a JWT token using Node.js?

In my MEAN stack authentication application, I am utilizing Node and Angular. After a successful login, I set a JWT token and store it in a session within the controller by assigning the token to config.headers through a service interceptor: var token = j ...

What steps do I need to take in order to ensure that when the word Hello is entered, the resulting output will display e:1, h:1, l:2, o:1

<!doctype HTML> <html> <body> <h3>Enter a string: </h3> <input id="myInput1" type="text"> <button onclick="count()">See output</button> //Click to see th ...

send another response following the completion of the request.end()

I am facing challenges with writing the correct callback function. The situation involves a user making a request to "/city", which then triggers the server to make a request to a third-party service for data retrieval using http.request(). I successfully ...

The styling of divIcons in React Leaflet Material UI is not applied as expected

When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet. Below you can find the code for the project ...

Challenges with the dropdown menu navigation bar

I am struggling with my dropdown menu and sign up/sign in buttons as they are not aligning properly. I have tried various coding methods but haven't been able to fix the issue. Can someone provide me with suggestions on how to rectify this problem? c ...