Popstate event Registered on body.onload works only after first mouse click on the document

Viewed 220

Steps to reproduce the problem:

  1. Place popstate event in all pages of your webapp and bind pop state event in body.onload and use history.pushState
  2. Navigate from myWebApp.page1 -> myWebApp.page2
  3. In page2 don't interact with the page(don't click on the page) just push browserback

What is the expected behavior?

popstate event fire before onunload event. this expected behavior is happing if the user interact with the page(click or type in page) before clicking the browser back.

What went wrong?

unload event occurs and browser send request to server

function disableBrowserBack(){
        history.pushState(null,null,null);
        onpopstate=function(){
        history.pushState(null,null,null);
        console.log('popstate')
        }
    }

This is function I call in body.unload.

Node.js serverFile

var http = require('http');

http.createServer(function (req, res) {
console.log(req.url);
res.write(`
<html dir="ltr" lang="en" class="focus-outline-visible"><head>
<meta charset="utf-8">
<title>New Tab</title>
<script>
    function disableBrowserBack(){
        console.log('page loaded');
        history.pushState(null,null,null);
        onpopstate=function(){
        history.pushState(null,null,null);
        alert('popstate')
        }
        onunload=function(){
            console.log('unload');
        }
    }
</script>
</head>
  <body style="background-color: rgb(255, 255, 255);" onload="disableBrowserBack()">
  <span><b>Hellow world</b></span>
</body></html>`); 
    res.end(); 
}).listen(8080); 
0 Answers
Related