SoFunction
Updated on 2025-04-10

Examples of using onload and onunload in js

introduction:
It's fine today. I remembered a B2C e-commerce platform I made before. There are still some things that are not perfected, so I thought about perfection. Well, the problem is this. There is a scenario in the e-commerce platform. I place the shopping cart in the Session so that it can get the shopping cart model from the Session throughout the shopping process. Some products in a certain type of shopping cart will be reduced in the database. However, if I close the window, how to add the number of products in the shopping cart model in the Session to the database. So I looked for GOOGLE and Baidu. The first prompt I got was: close the window to automatically clear the Session. So the first method I found was to use the onunload attribute in the <body> tag and call a certain js such as: <body onunload=”close()”>This method triggers the close() event when the window is closed, so I can define a method to delete the Session in the close() method...
But this is not the case. Onunload will trigger when you refresh this page and click on the link on this page. So I searched it again in GOOGLE and Baidu: The answer I got is as follows:
Copy the codeThe code is as follows:

<script>
= function(){if(>9000)alert('This window has been closed!')}
</script>
or
<script>
= function(){if(>9000)alert(This window has been closed!.')}
</script>

illustrate:

Get the y coordinates of the upper left corner of the browser client area relative to the upper left corner of the screen
screenTop>The following numbers must be greater than the height in your display resolution
For example, 800*600, this number must be greater than 600

Get the x coordinates of the upper left corner of the browser client area relative to the upper left corner of the screen
screenLeft>The following numbers must be greater than the width in your display resolution
For example, 800*600, this number must be greater than 800

Usually these two values ​​are set to 9000
So I used the above method to achieve that the onunload event is triggered only when the page is closed.

Summarize:
① When using the onunload property, you can use Ajax to clear the Session, or use it to trigger a request. For example, I am using struts2 in this, I can use <body onunload="javascript:-'${ }/cart/'" >
Then there is a request to process the goods in the shopping cart in the Session and add their quantity to the database;
② I also have Ajax to handle the request here, but in fact, we only need to process the Session and do not have any asynchronous information returned after the Session. So I still use the method of triggering a request. The final writing method is as follows:
Copy the codeThe code is as follows:

<body
onunload="javascript:if(>9000) ='${ }/cart/';">