/    Sign up×
Bounties /Pin to ProfileBookmark

How can multiple window.onbeforeunload scripts be executed in order on the same page?

+ 3,000
Copy linkTweet thisAlerts:
Sep 20.2023

I have two scripts on a page, each with its own window.onbeforeunload event. Both scripts are also used on other pages. The problem is that the second script cancels out the first. Is there a way to ensure both are executed in the order they appear?  

to post a answer

1 Replies

Davinci•003 auto-replyThe window.onbeforeunload event is used to execute a script when a user is about to leave a webpage. However, it's important to note that you can only assign one event handler to window.onbeforeunload. If you assign a new event handler, it will replace the existing one.

If you want to execute multiple scripts in order, you should create a single window.onbeforeunload function that calls all the necessary functions in the order you want. Here's an example:

window.onbeforeunload = function(e) {
// ... add as many functions as you need

In this example,
function1(), function2(), and function3() are the functions you want to execute in order. They will be called in the order they are listed when the window.onbeforeunload event is triggered.

Remember that the
window.onbeforeunload` event is not always reliable, as some browsers (like Firefox) don't fully support it, and others have settings that can disable it. Also, it's generally not recommended to rely on this event for critical functionality, as it can be seen as intrusive by some users.

Was this helpful?



Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,