Javascript distinguishes whether browser pages are refreshed or closed _ javascript skills

Source: Internet
Author: User
In web development, we often have various requirements. Today, I want to tell you how to refresh or close tabs on a browser page in Javascript. It is very practical. If you are interested, refer to the following section. Web developers often have to deal with various requirements of product managers in system development, of course, most of them are helpful to the product experience. For example, when we refresh the page today and move forward and backward, we need to provide a prompt box for Secondary confirmation to avoid user misoperations when closing the browser tag, I believe everyone is very familiar with this. We can solve this problem by using the BOM event mechanism provided by the browser. We can use the onbeforeunload event of the window object. If the product manager only raises this requirement, it is indeed understandable, however, it requires more than just these...

For example, during a project development, the product manager proposed an "Improvement Solution" for our implementation ":

The pop-up box is too ugly. It doesn't 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...

Refresh is the same as the text displayed on the close tab. You need to refresh the XXX prompt and the SSS prompt when the tab is closed so that the user can be clearer. Well, considering the user experience, it's good. I still want to say, you can you up... in fact, when the browser is closed and refreshed, it is already treated differently. The prompts are different, but the custom part cannot display different texts. Of course, there are also some hack methods, but it is difficult to adapt to multiple browsers. The implementation mechanisms for closing tabs and refreshing are different in each browser;

Every time you log in, why does it take 10 seconds for the agent to sign in to the telephone system? (we are working on the customer service system )? Can you remove this restriction? The user experience is too bad! We also want to remove it. However, frequent check-in and check-out by the telephone system may cause problems. The user refresh the browser and re-signs the check-in. If the time is short, the telephone system may fail. To avoid this problem, we have added this restriction, but when we look back, we can enter the topic we are discussing today;

Differentiate between refresh and close tabs

We cannot identify whether to refresh or close tabs Based on browser events, and then execute different actions before the corresponding action is triggered. However, for the third opinion of the product mentioned above, in fact, we can still consider optimizing it, that is, there is only a delay of 10 seconds during refresh, and there is no delay when a new login or tab is closed for a period of time before it comes in;

To do this, it is actually very simple. You can use the local storage mechanism of the browser, such as cookie and LocalStorage. SessionStorage cannot be used here, because after this session, the cache becomes invalid. because the number of bytes of the cookie is increased when the cookie is stored, the corresponding network transmission volume increases in each request. Therefore, we use LocalStorage. The operation is very simple, the front-end framework we use is AngularJS. The details are 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 above code is mainly used to obtain the time of the last exit from LocalStorage and the current time after entering the system. The two time periods are subtracted. If the value is less than 10 seconds, we think this is a refresh. If the value is greater than 10 seconds, we think it is to close the tab or log on, and then we can execute different methods to give our customer service a better experience, you don't have to wait for 10 seconds to check in the phone system every time you enter the system. The product manager is very important, maybe we won't optimize this place... of course, in fact, RD should gradually cultivate this kind of user experience-oriented thinking, even if there is something that can improve customer service efficiency, it is worth our time to optimize;

I will also paste the relevant exit code below. I forgot to mention that, whether refreshing or disabling tabs, We will log out of the phone system as long as the page is destroyed, therefore, you need to re-sign in every time you come in;

// Refresh the page or close the page $ window. onbeforeunload = () => {return 'operation will result in page data clearing. Please proceed with caution... ';}; // set LocalStorage time each time the page is unloaded; $ window. onunload = () =>{ $ window. localStorage. setItem ('lastleavetime', new Date (). getTime ());};

We may also notice some problems, that is, refresh, close the page, and move forward and backward. You need to jump out of the browser's default Secondary confirmation box, but the user clicks the exit system button, the Dialog in the component library must be displayed, and neither of them must be displayed. The specific code is as follows:

OnStatusClick (index, name) {if (name = 'logout ') {this. mgDialog. openConfirm ({showClose: false, template: 'app/header/logoutDialog.html ', controller: 'headerdialogcontroller as dialog', data: {'title': 'Are you sure you want to exit the system? '}}). Then () => {this. $ window. location. href = '/logout'; this. $ window. onbeforeunload = null;});} else {// internal operation, no need to worry about ...}}

The above section shows you how to refresh or close the Javascript browser page. I hope it will help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.