Home > Article > Web Front-end > JS distinguishes whether the browser page is refreshed or closed_javascript skills
Web developers often face various demands from product managers during system development. Of course, most of them are helpful for product experience, such as refreshing the page, going forward and back, and closing the browser we mentioned today. When labeling, in order to avoid user misoperation, a secondary confirmation prompt box needs to be given. I believe everyone is very familiar with this. It can be solved by using the BOM event mechanism provided by the browser. Just use the onbeforeunload event of the window object. If the product manager It is understandable to only raise such demands, but it requires more than just these...
For example, during one of our project developments, the product manager proposed an "improvement plan" for our implementation:
Your pop-up box is too ugly and does not match the overall style of the system. Can't we use the Dialog in our own component library? Very good question...I just want to say, you can you up...
The copy displayed in your refresh and close tabs is the same. They need to be treated differently. The refresh prompt is XXX and the SSS prompt is prompted when closing, so that users can be more clear. Well, considering the user experience, it's very good. I still want to say, you can you up... In fact, the browser itself has treated it differently when it is closed and refreshed. The prompts are different, but we have customized them. Some parts cannot display different copywriting; of course, there are some hack methods, but it is difficult to adapt to multiple browsers, and the internal implementation mechanism of closing tabs and refreshing will be different in each browser;
Every time you log in, why do you have to delay 10 seconds before letting the agent log in to the phone system (we are a customer service system)? Can you remove this restriction? The user experience is so bad! We also want to remove it, but frequent check-in and check-out of the phone system will cause problems. If the user refreshes the browser and checks in again, if the interval is very short, the phone system will malfunction. In order to avoid this problem, we added We have overcome this limitation, but if we think about it again, we can enter the topic we discussed today;
Distinguish between refreshing and closing tabs
We cannot distinguish between refreshing or closing tabs based on browser events, and then perform different actions before the corresponding action is triggered. However, regarding the third point raised by the product above, we can actually consider optimizing it, that is, only There is a 10-second delay when refreshing. There will be no delay when logging in again or after closing the tab for a while;
It is actually very simple to do this. You can use the browser's local storage mechanism, such as cookies, LocalStorage, etc. SessionStorage cannot be used here because the cache will be invalid after this session ends; Since storing in cookies will increase the number of bytes of the cookie, the corresponding network transmission volume in each request will increase. Therefore, we use LocalStorage; its operation is very simple. The front-end framework we use is AngularJS, as follows:
const MAX_WAIT_TIME = 10; const currentDate = new Date().getTime(); const lastestLeaveTime = parseInt(this.$window.localStorage.getItem('lastestLeaveTime'), 10) || currentDate; this.secondCounter = Math.max(MAX_WAIT_TIME - Math.ceil((currentDate - lastestLeaveTime) / 1000), 0); if (this.secondCounter > 0) { this.logoutTimeInterval = this.$interval(()=> { this.secondCounter--; this.$scope.$digest(); }, 1000, this.secondCounter, false).then(() => { this.updateByStatus(this.AvayaService.status.OFFLINE); }); } else { this.updateByStatus(this.AvayaService.status.OFFLINE); }
The main function of the above code is that after entering the system, it will first go to LocalStorage to get the time when it was last exited, and then get the current time, and subtract the two times. If the value is less than 10 seconds, we think it is a refresh. If the value is greater than 10 seconds, we think it is a close tab or a new login, and then we can perform different methods to give customer service a better experience. We don’t have to wait 10 seconds every time to log in to the phone system. Product Manager It's still very important, Hoho. If it weren't for his questions, we might not have optimized this place... Of course, in fact, RD must gradually cultivate this kind of user experience first thinking, even if it can improve customer service efficiency a little bit Every place is worth our time to optimize;
Let me post the relevant exit code below. I forgot to mention it before. No matter it is refreshing or closing the tab, as long as the page is destroyed, we will perform the operation of logging out of the phone system, so every time we come in, we need to Check in again;
//刷新页面或者关闭页面 $window.onbeforeunload = () => { return '操作将会导致页面数据清空,请谨慎操作...'; }; //每次页面unload时,设置LocalStorage时间; $window.onunload = () => { $window.localStorage.setItem('lastestLeaveTime', new Date().getTime()); };
We may also notice some problems, that is, refreshing, closing the page, forwarding and backing, you need to jump out of the browser's default secondary confirmation box, but when the user clicks the exit system button, the Dialog in his own component library must pop up. Both must not pop up. The specific code is as follows:
onStatusClick(index, name) { if (name === '退出') { this.mgDialog.openConfirm({ showClose: false, template: 'app/header/logoutDialog.html', controller: 'HeaderDialogController as dialog', data: { 'title': '您确定要退出系统吗?' } }).then(() => { this.$window.location.href = '/logout'; this.$window.onbeforeunload = null; }); } else { // 内部操作,大家不用管 ... } }
The above is the entire content of the JS introduced by the editor to distinguish whether the browser page is refreshed or closed. I hope it will be helpful to everyone!