简体   繁体   中英

How can I replace window.onbeforeunload with custom code?

For accessibility reasons, for my Chrome extension, I need to be able to replace all standard window.onbeforeunload popups with an in-page HTML substitute. I know how to create a substitute skeleton, that's trivial.

And I know the basic idea here is window.onbeforeunload = {my substitute code} .

What I don't know how to do is grab the text and code from each confirmation window that a page issues, and channel it into my substitute, so that the same message is shown as would be in the original popup and clicking my substitute confirm and leave page (or whatever) buttons yield the same result as the original popup.

How can this be done?


EXAMPLE:

You have my extension installed (don't ask what its purpose is, irrelevant).

You start writing a question on StackOverflow, then realize you already know the answer and go to close the tab.

Normally, a confirmation window would come up asking if you're sure you want to leave the page.

But because of my extension, instead, the whole page's HTML gets shoved down a bit to make room for a temporary HTML confirmation box is shown with the same text and the same two buttons that yield the same two results when clicked, all in-page. No pop-up.

The feature you're talking about is the window.onbeforeunload event, and unfortunately the only way it can be customized is to provide a custom string message for the user, because the potential for abuse is so high.

The api reference over at msdn for Internet Explorer states:

The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.

I take this to mean the dialog itself cannot be altered, all you can do is provide an additional context-specific message. I cant locate the same reference for Chrome, but it seems to be the same story there.

window.onbeforeunload = function() {
    //all you can do is provide a message..
    return "you have unsaved changes, if you leave they will be lost";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM