Detecting when a user navigates backwards on a mobile device using JavaScript

I am currently working on a basic HTML file that includes a JavaScript code snippet:

<p>Press The Back Button and see a message!</p>

<script>
window.onpopstate = function(event) {
    alert("location: " + document.location);
}
</script>

Running Android 11 and the latest version of Google Chrome, I encounter an issue where pressing the back button does not trigger the desired alert displaying the location.

https://i.sstatic.net/ld9IM.png

Seeking advice on how to troubleshoot this problem and make the code work as intended. Any suggestions would be greatly appreciated!

Answer №1

When the navigation history changes, the onpopstate event is triggered as long as your current code does not alter the history state.

To ensure that the onpopstate event is activated when the Back button is pressed, you can push a state onto the history stack immediately using window.history.pushState():

<script>
window.history.pushState({page: 1}, "", "#nogo");
window.onpopstate = function(event) {
    alert("location: " + document.location);
}
</script>

By clicking the back button, the history state is altered, subsequently triggering the onpopstate event.

Important: The inclusion of #nogo in the state prevents the page from scrolling when a new history state is added.

Answer №2

<script>
    function handleHistoryState() {
        window.history.pushState({ page: 1 }, "title 1", "#state1");
    }

    window.onpopstate = function(event) {
        alert("Current location: " + document.location);
    };

    window.onload = function() {
        handleHistoryState();
    };
</script>

By using the window.onpopstate event correctly, you can manage the back button and display an alert with the current location. The onpopstate event is triggered only when there is a change in the active history entry. This means simply clicking the back button won't trigger the event unless the history stack has been modified using history.pushState() or history.replaceState().

Feel free to try out this code. It should address your issue. If you encounter any difficulties, don't hesitate to contact me for assistance.

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

send a JSON string as a parameter to a JavaScript function

After receiving a valid JSON string (JSONP) from my server, I needed to parse it on the client side. Here is an example: parseJSON({ "NAME": "Tom" }); I have implemented this function on the client side: function parseJSON(myOBJ) { //myOBJ is alrea ...

Incorporating modules through System.JS

I integrated angular2-google-maps into my Angular 2 application for utilizing Google Maps functionality. Here is a snippet from my package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurre ...

Executing PHP function through AJAX

I have thoroughly researched various resources regarding my issue but still have not been able to find a solution. My goal is to retrieve the result of a PHP function using jQuery AJAX. function fetch_select(){ val_name = $('#name').val(); ...

Separating vendor and application code in Webpack for optimized bundling

Recently, I created a React+Webpack project and noticed that it takes 60 seconds to build the initial bundle, and only 1 second to append incremental changes. Surprisingly, this is without even adding my application code yet! It seems that the node_modules ...

Receive immediate updates of the text input in real-time using the onkeydown event handler in Javascript

I attempted to display the content of the input box in a message div simultaneously, however, the output always seems to be one step behind. function showWhatsWritten(){ var tempText; tempText = document.getElementById("text").value; document.getEle ...

Avoid revealing sensitive information by refraining from utilizing the Json decode() function

After successfully storing values in an HTML table to a MySQL database, I encountered an issue when trying to fetch the data using Json decode(). The HTML table did not display any data on the web page, and there were no errors thrown. Below is the PHP co ...

useEffect is triggered despite there being no change in the state

const [urlList, setUrlList] = useState(0); const callDayList = () => { console.log(urlList); Axios.post('http://localhost:3001/api/get', { passNum: urlList, }); }; useEffect(callDayList, [urlList]); <td> <Link ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

Can you explain the distinction between "(.....);" and "{......}" within the context of React?

Encountering an error indicated in the image for the following code: handlechange(event) { this.setState (prevState => { return( checked : !prevState.checked );}); } Interestingly, changing the round brackets after "return" to curl ...

Is there a secure way to prevent user input from causing issues in a BigQuery node insert? Can the BigQuery.insert node library support parameterized queries for added security

I am seeking advice on how to securely insert user form data into BigQuery using the Google Cloud BigQuery library. Specifically, I am curious about the most effective methods for sanitizing, escaping, and cleaning the input data. Is it feasible to implem ...

Unsupported server component type: undefined in Next.js version 13 is not recognized by the server

Encountered some unusual behavior in Next.js 13 while attempting a simple action. I have provided a basic example demonstrating the issue. Seeking assistance in understanding why this is occurring. This scenario involves 3 components: page: import {Conta ...

Automating button clicks after a component has loaded in Angular 2+ can be achieved by implementing a

Currently, I am working on implementing an automatic search function in Angular that triggers after a component loads. Right now, the function is triggered by a button click, but I want to automate this process. <button mat-raised-button class="mat-whi ...

Embedding JQuery within a PHP file

Recently, our inventory web page was coded in PHP by someone else. I've been working on integrating a jQuery function into the webpage that displays a description whenever a barcode is scanned. While testing on jsbin.com everything works perfectly, bu ...

Can you explain the distinctions among <Div>, <StyledDiv>, and <Box sx={...}> within the MUI framework?

When exploring the MUI documentation, I came across a table of benchmark cases that can be found here. However, the differences between the various cases are not clear to me. Can someone please explain these variances with real examples for the following: ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

JavaScript does not support ActiveX events

I am having an issue with the following code on my website. The C# ActiveX code works fine, but the events do not seem to be working properly. Can you help me identify what I may have done wrong? <object id="MyCC" codebase="http://localhost:3239/WebD ...

When passing context to createPage for use in a query, there may be issues if a string is inadvertently converted to a number, causing the query to fail

I am facing an issue with a page creation function that I have implemented. Here is the code snippet: createPage({ context: { productId: String(productId) }, Despite explicitly converting the ID to a string, the page template is still receiving it as a ...

The jScrollPane fails to remain at the bottom

I have implemented jScrollPane for the scrollbars in a chat interface that I created. However, I am facing an issue where the scroll does not automatically go to the bottom as expected. I have set the 'stickToBottom' option to true and also enabl ...