-4

I have a js plugin that redirects the page after successful action.

I want to catch page unload and redirect to my own url.

I tried using beforeunload event, but I can't use it because it just asks the user if it's ok with him to leave the page. Not quite what I'm looking for.

It does not matter what the plugin does, the question is:
Is it possible to catch page redirect event, and redirect to another url instead?

Hike Nalbandyan
  • 994
  • 1
  • 11
  • 28
  • 2
    A "plugin" to what? A browser plugin/addon/extension? If so, what kind? The capabilities of browser addons/extensions vary by browser. – T.J. Crowder Mar 04 '19 at 11:22
  • You can't and with a good reason. If the user wants or needs to leave the page, the only thing you can do is to ask him not to. But if he confirm, he should be able to leave. – Mosh Feu Mar 04 '19 at 11:25
  • At least related: https://stackoverflow.com/questions/15893770/how-to-redirect-page-when-user-close-tab-or-window, https://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event – T.J. Crowder Mar 04 '19 at 11:35

2 Answers2

0

If you mean that you want to do this in code in a web page (not a browser extension), you can't. If the user wants to close the page or navigate to a different page, there is nothing your JavaScript code in the page they're leaving can do to prevent it. It was something scummy websites tried to do early on, which is now appropriately prevented by browsers.


(I'd be surprised if you could do it in a browser extension, either, but they do have more capabilities than normal web pages do.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Is something like this your intended behaviour?

document.onbeforeunload = function (e) {
  var e = e || window.event;
  e.returnValue = "sure?";
}
var test = document.getElementById("reload_test");
  test.onclick = function () {
  document.onbeforeunload = function(){};
}

I'm creating the leaving prompt, but emptying the "onbeforeunload" method when you try to move to another webpage.

JSFiddle seems to work as you intended (could have some issues on some other browsers since I don't know how they handle the "onbeforeunload" event).

JSFiddle

H. Figueiredo
  • 888
  • 9
  • 18