If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Prompt in JavaScript

Started by itraider, 05-23-2010, 18:30:10

Previous topic - Next topic

itraiderTopic starter

What i want is, when a user leaves or clicks back button there should be a prompt which asks him if he wants to visit another site. If he clicks yes then the page should be redirected. If clicks no then the browser closes or goes to back whatever the visitor has clicked. (x or back button)

But it should not happen when user submits the form or visits internal link.

please don't suggest me not to do this, i dont care if its irritating as its for my client so its my humble request to all the js pros to help me asap.
  •  


redwolf

To achieve the desired functionality, you can use JavaScript's `beforeunload` event. This event is triggered when a user navigates away from the current page. However, please note that this feature can be intrusive and may not work in all browsers.

Here's an example of how you can implement the prompt:

```javascript
window.addEventListener('beforeunload', function(e) {
  // Cancel the event to prevent the default browser behavior
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';

  // Check if the user is submitting a form or visiting an internal link
  if (e.target.tagName !== 'FORM' && !e.target.href) {
    // Show the confirmation prompt
    let confirmationMessage = 'Do you want to visit another site?';
    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;
  }
});
```

In this example, the `beforeunload` event listener cancels the event and shows a confirmation message when the user navigates away from the page but is not submitting a form or visiting an internal link. If the user confirms their intention to visit another site, the page can be redirected with `window.location.href = 'https://example.com';`.

Keep in mind that some browsers may block custom messages or display a generic message instead. Additionally, users can often disable these prompts in their browser settings.
  •  


If you like SEOmastering Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...