JavaScript pageshow Event: A Comprehensive Guide

The pageshow event in JavaScript is a critical part of the page lifecycle events. It fires whenever a page is displayed, including when the page is initially loaded, and when the user navigates back to the page using the browser’s history (back and forward buttons). Understanding the pageshow event is crucial for handling page visibility changes and maintaining the proper state of your web applications.

What is the pageshow Event?

The pageshow event is triggered when a page becomes visible on the screen. This can happen under various circumstances:

  • Initial Page Load: When the page is loaded for the first time.
  • History Navigation: When the user navigates back to the page using the back or forward buttons.
  • Restored Page: When a page is restored from the browser’s cache.

This event is complementary to the pagehide event, which fires when a page is about to be hidden. The pageshow event is useful for performing setup or update tasks after the page becomes visible.

Purpose of the pageshow Event

The primary purpose of the pageshow event is to:

  • Handle Initial Page Setup: Execute scripts to initialize the page’s UI.
  • Restore Page State: Reestablish the previous state of the page after returning from history.
  • Update Data: Refresh content when navigating back to the page.
  • Manage Session State: Handle session-related tasks when the user navigates through the browser history.

Syntax and Usage

The pageshow event is an event of the window object. You can attach an event listener to it using the addEventListener method or by setting the onpageshow property directly.

Using addEventListener

window.addEventListener('pageshow', function(event) {
  // Code to be executed when the page is shown
});

Using the onpageshow Property

window.onpageshow = function(event) {
  // Code to be executed when the page is shown
};

pageshow Event Properties

The pageshow event includes an event object that has a crucial property, persisted:

Property Type Description
`type` String Returns the name of the event i.e., “pageshow”.
`target` Object Returns the element that triggered the event (window).
`persisted` Boolean Indicates whether the page was loaded from the browser’s cache/history (true) or as a new load (false).
`timeStamp` Number The number of milliseconds elapsed since the document loaded.

The persisted property allows you to differentiate between a new page load and a page restored from the browser’s history or cache. This differentiation is particularly useful when you need to avoid re-initializing elements or making unnecessary network requests.

Examples

Let’s explore various ways to use the pageshow event with practical examples.

Basic Usage

The following example demonstrates how to display an alert message when the page is shown, both on initial load and when navigating back.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pageshow Event Example</title>
</head>
<body>
    <h1>Pageshow Event Example</h1>
    <script>
        window.addEventListener('pageshow', function(event) {
            alert('Page is shown!');
        });

</script>
</body>
</html>

When you first load the page, the alert message will display. If you navigate away from the page and then click the back button, the alert message will display again.

Differentiating Between New Load and Restored Page

The persisted property allows you to handle a new page load and a restored page from history differently.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pageshow Event - Persisted Property</title>
</head>
<body>
    <h1>Pageshow Event - Persisted Property</h1>
    <div id="statusDisplay"></div>
    <script>
        const statusDisplay_persist = document.getElementById('statusDisplay');
        window.addEventListener('pageshow', function(event) {
            if (event.persisted) {
              statusDisplay_persist.textContent = 'Page restored from history!';
            } else {
              statusDisplay_persist.textContent = 'Page loaded for the first time!';
            }
        });

</script>
</body>
</html>

When you initially load the page, the message will indicate it’s the first load. If you navigate away and then return, the message will indicate the page was restored from history.

Using pageshow to Restore Form Data

This example demonstrates how to use the pageshow event to restore form data when navigating back to a page.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Restore Form Data</title>
</head>
<body>
  <h1>Restore Form Data</h1>
  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <button type="submit">Submit</button>
  </form>
  <script>
    const form_restore = document.getElementById('myForm');

    function saveFormData() {
      localStorage.setItem('formData', JSON.stringify({
        name: form_restore.elements.name.value,
        email: form_restore.elements.email.value
      }));
    }

    form_restore.addEventListener('submit', function(event) {
      event.preventDefault();
      saveFormData();
      alert('Form submitted! Navigate away and come back to see the data persisted.');
      window.location.href = '#'; // Navigate away for demonstration
    });

    window.addEventListener('pageshow', function(event) {
      if (event.persisted) {
        const formData_restore = localStorage.getItem('formData');
        if (formData_restore) {
          const data = JSON.parse(formData_restore);
          form_restore.elements.name.value = data.name;
          form_restore.elements.email.value = data.email;
        }
      }
    });

</script>
</body>
</html>

Here’s how the example works:

  1. Data persistence: On submit, the form data is saved to localStorage as JSON.
  2. Restore form data: When the page is shown (navigated back to using the browser’s back button), the stored form data is retrieved from localStorage and repopulated in the form fields if the event is persisted.

Using pageshow with Canvas

The pageshow event can also be used with HTML Canvas elements. This is particularly useful when you want to maintain the state of a canvas when navigating back and forth.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas and Pageshow</title>
</head>
<body>
  <h1>Canvas and Pageshow</h1>
  <canvas id="myCanvas_pageshow" width="200" height="100" style="border: 1px solid black;"></canvas>
  <button id="drawButton">Draw Rectangle</button>
  <script>
    const canvas_pageshow = document.getElementById('myCanvas_pageshow');
    const ctx_pageshow = canvas_pageshow.getContext('2d');
    const drawButton_pageshow = document.getElementById('drawButton');
    let isCanvasDrawn = false;

    function drawRectangle() {
      ctx_pageshow.fillStyle = 'lightblue';
      ctx_pageshow.fillRect(10, 10, 100, 50);
      isCanvasDrawn = true;
    }
    drawButton_pageshow.addEventListener('click', drawRectangle);

    window.addEventListener('pageshow', function(event) {
        if (event.persisted) {
        if (isCanvasDrawn) {
            drawRectangle();
        }
      }
    });

</script>
</body>
</html>

Here’s what this example does:

  1. Initial Canvas drawing: On click on the Draw Rectangle button, a rectangle is drawn on the canvas.
  2. Canvas Persistence: When the page is shown via back/forward buttons the canvas is redrawn using the pageshow event listener based on the isCanvasDrawn variable if the pageshow event persisted is true.

Note: You can save the isCanvasDrawn value also in local storage and then read it back to persist this information across sessions. 💡

Browser Support

The pageshow event is supported across all modern browsers. It is an important part of the web platform.

Browser Supported
Chrome Yes
Firefox Yes
Safari Yes
Edge Yes
Opera Yes
IE 9+

Key Considerations

  • Event Listener Management: Make sure event listeners are added appropriately and avoid adding them multiple times.
  • Performance: Avoid heavy operations inside the pageshow event handler to prevent slow loading or performance issues.
  • User Experience: Use the persisted property to restore states in a way that is seamless to the user.
  • Caching: When using pageshow, keep in mind that some browsers might cache pages, and you should handle the event for both new loads and history navigation.

Conclusion

The JavaScript pageshow event is a powerful tool for managing page visibility and maintaining state across page transitions. By differentiating between a new page load and a page restored from history using the persisted property, you can handle user interactions effectively and create a more seamless and responsive user experience. Understanding and using the pageshow event correctly can significantly enhance the overall quality and functionality of your web applications.