JavaScript + onbeforeunload

后端 未结 6 1291
盖世英雄少女心
盖世英雄少女心 2020-11-30 09:30

I have a query regarding my application. Whenever user closes browser window accidentally I\'d want to do some clean up operations before that. I have used onunload event bu

6条回答
  •  旧时难觅i
    2020-11-30 10:34

    This works:

    window.onbeforeunload = function(){
        console.log('closing shared worker port...');
        return 'Take care now, bye-bye then.';
      };
    

    This is handy if, for instance you're working with SharedWorkers and you need to tell the worker that there is one less port to manage -- otherwise, you could end up refreshing one browser tab and get something like a "Successfully connected with: 10 other tabs" because the one tab is keeping the worker alive while the other tab's refreshes keep pushing new port connections to you array.

    Hope this helps.

提交回复
热议问题