Running specific code after a page refresh in Javascript: How to achieve this?

Important: While it could be achieved with PHP (I'm using WooCommerce on Wordpress), I prefer running this script only in my browser using Javascript. Hence, I am utilizing Custom Javascript for Websites to execute the script from my browser.

The Objective of My Script: To check if the data of a specific element has been altered.

Concept: Step 1) Obtain and locally store a particular string (order number) of a specific class. Step 2) Refresh the page. Step 3) Retrieve the specific string (order number) of a specific class again. Step 4) If the strings do not match, trigger a function (play an audio).

Challenge: After the page reloads, the script initiates execution from the beginning, causing the stored string to get overridden. Consequently, the stored and freshly fetched strings are always identical.

Inquiry: How can I ensure the script runs the 3rd step only after a refresh so that the stored data remains intact without getting overwritten?

Current Implementation:

var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Obtain the last element of the string
localStorage.setItem("compareOld", compareOld); // Store this element in local storage for future use.

setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.

var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new variable.
var n = compareOld.valueOf(); // Convert stored element into a number for easy comparison later.

var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Obtain the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Extract the last element of the string
var m = compareNew.valueOf(); // Turn retrieved element into a number

function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAE...SS6l/");
    snd.play();
} 

if (n != m) {
    beep();
}

Addendum: The code snippets have been curated from various resources including StackOverflow. This marks my initial inquiry. I hope the question is clearly presented and understandable.

UPDATE: The issue has been resolved by implementing the concept of executing the first step of the function only during the initial page load. Reference from this response helped me achieve the desired functionality:

The updated functional code::

function beep() {
    window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}

if (sessionStorage.getItem("visit") == null) {
    var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
    sessionStorage.setItem("OrderIdOld", OrderIdOld);
    sessionStorage.setItem("visit", new Date());
    setTimeout("window.location.reload()", 10000);
}

else {
    var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
    var x = sessionStorage.getItem("OrderIdOld");
    if (x == OrderIdNew) {
        setTimeout("window.location.reload()", 10000);
        }
    else {
        beep();
        var x = sessionStorage.getItem("OrderIdOld");
        sessionStorage.removeItem("OrderIdOld");
        sessionStorage.removeItem("visit");
        setTimeout("window.location.reload()", 10000);
    }
}   

Answer №1

To differentiate between a refresh and a first-time load when refreshing the page for the first time, add a flag variable to the URL. Utilize this flag variable to determine whether to pass a localized variable to the script in order to trigger a refresh or not.

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

What is the best way to create a search bar that can dynamically update the content on another page or component using Next.js?

I have some unchanging information that I exhibit on the table page. Overall, my application has numerous pages. data.json: [ { "title": "Item 1", }, { "title": "Item 2", } ... ] Table page: import ...

How can Cognito be integrated on a pure HTML & JS website, with or without using Amplify?

After diligently reading through the documentation provided by AWS which mainly focuses on React JS, I am feeling a bit lost. My goal is to set up the sign-in, sign-up, and login components but the process seems complex. I stumbled upon an alternative met ...

What is the best way to merge the values of an array into one variable?

I am facing an issue with handling an array containing objects with two nested nodes, "name" and "title". The array includes product attributes such as "size", "style", "colors", etc. All of these attributes are stored in a single array. My goal is to dyna ...

Encountering a "404 not found" error when trying to access `/en/first` with the routing

I am currently working on setting up a routing module in Node.js & express, but I seem to be encountering some issues. The specific error message I am getting is Cannot GET /en/first The goal is to organize different folders like 'en', each wit ...

What is the best way to achieve a hover effect on rows in material-table using react?

I have implemented material-table in my React project to display my data. I am looking to add hover and cursor pointer effects when hovering over rows, but I haven't found a straightforward solution in the documentation. TO SUMMARIZE- I want to highl ...

How to structure a URL to retrieve JSON data from an API using the fetch method

As a newcomer to working with APIs and data retrieval methods, I have been exploring tutorials such as this one on the fetch method or using the XMLHttpRequest method. While I have had success with the APIs used in these tutorials, I have run into difficul ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

Execute PHP script via hyperlink

Is there a way for me to have a small PHP script that only gets the current page URL and echoes it when a user clicks on a submit button? I'm struggling because there are no other form items on the page, making it difficult to trigger the script. I th ...

Creating an input in Vue3/Javascript that restricts input to only numbers seems to be a challenge

I have a project that involves an input field which should only accept numerical values. Within the template, I've set up an input element with the value bound to a variable and the input event linked to a function that verifies if the entered value ...

Determine future dates based on selected date and time

When a user selects a date in the datetimepicker, I want to automatically set three additional dates. The first date will be the selected date + 28 days, the second date will be selected date + 56 days, and the third date will be selected date + 84 days. I ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

How to generate flexible arrays using an established array?

Currently, I am working on creating a new array from an existing one. The structure of my current array is outlined below. How can I ensure that adding a new object results in a new array starting from that point? myArray: [{ anima ...

When dynamically mapping in ReactJS, only select classes in Tailwind CSS are applied

I am currently developing a React component for the navigation bar on my personal website. To keep track of each navbar item's name, color, and link, I am utilizing an array called navItems: const navItems = [ { name: "home", color ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Preserve the table's state even after submitting the form

My php page initially displays a table by default, which is: echo "<table class='tftable' border='1' id='table_L'>"; There is also another table: echo "<table class='tftable' border='1' id=&apos ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

Attempting to implement a while loop in React to render a specified number of elements before adding an additional element

I've been developing a React app that showcases 20 products initially, followed by an advertisement. Once you reach the end of the displayed products, another set of 20 products along with another ad are shown. In order to achieve this functionality, ...

Dynamic height of a fixed-positioned Div

I encountered an issue with a Fixed positioned DIV that has dynamically appended content using jQuery. Once the height of the DIV exceeds the screen size, I am unable to view the contents at the bottom of the DIV without zooming in using the browser' ...

Guidelines for choosing AngularJS checkboxes to exclusively choose distinct matching items

Need help with selecting common items using Angular checkboxes. Below is the mock UI-Table: Order Id | Delivery Mode | Select 1 | Speed | ::checkbox:: 2 | Normal | ::checkbox:: 3 | Contractor | ::che ...