How to Go Back to Previous Page in Javascript

.
 
 

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <h1>Home Page</h1>
        <a href="/page1.html">Page 1</a>
        <a href="/page2.html">Page 2</a>
    </div>
    
</body>
</html>

 

Page 1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <h1>Page 1</h1>
        <button>Go Back</button>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

Page 2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <h1>Page 2</h1>
        <button>Go Back</button>
    </div>

    <script src="script.js"></script>
</body>
</html>

 

CSS:

body {
    text-align: center;
}

 

Javascript:

let btnBack = document.querySelector('button');

btnBack.addEventListener('click', () => {
    window.history.back();
});

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •