Intercept when a user is about to leave a navigation page

95 Views Asked by At

I would like to intercept when a user is about to leave the product page of my site, to make a personalized message appear in a modal.

I tried the 'beforeunload' event handler but it appears, in FireFox, a confirmation message about the desire to leave the page, default by the browser and being able to customize only the text; In Edge, does not show a confirmation message to leave the page but allows the user to continue browsing elsewhere regardless of the preventDefault().

Is there another event handler or a way to make this modal appear without getting the warning from the browser?

thanks!

   window.addEventListener('beforeunload', (e) => {
      e.preventDefault();
      let page_name = prestashop.page.page_name;

      if (page_name == 'index') {
        const modalProductPage = `
  <div class="jumbotron">
  <h1 class="display-4">Hello, world!</h1>
  <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
  <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
  <p class="lead">
  <a class="btn btn-primary btn-lg" href="#" role="button">Buy</a>
  </p>
  </div>
  `
        setTimeout(() => {
          console.log('event attived!')
          $('.modal-body').html(modalProductPage)
          $('#exampleModalCenter').modal('show')
        }, 500);

      }
    })
0

There are 0 best solutions below