2016-12-05 5 views
2

У меня есть компонент vue для загрузки видео, где я предупреждаю пользователя, когда он пытается уйти во время загрузки видео, чтобы он потерял файл, если он это сделает, например:Javascript - предотвращение навигации во время загрузки файла

 ready() { 
      window.onbeforeunload =() => { 
       if (this.uploading && !this.uploadingComplete && !this.failed) { 
        this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!'); 
       } 
      } 
     } 

Я использую sweetalert, чтобы предупредить пользователя об этом. Но как я могу заставить его остаться на одной странице и предотвратить навигацию, прежде чем он подтвердит, что он хочет уйти?

Это весь компонент:

<script> 
    function initialState(){ 
     return { 
      uid: null, 
      uploading: false, 
      uploadingComplete: false, 
      failed: false, 
      title: null, 
      link: null, 
      description: null, 
      visibility: 'private', 
      saveStatus: null, 
      fileProgress: 0 
     } 
    } 
    export default { 
     data: function(){ 
      return initialState(); 
     }, 
     methods: { 
      fileInputChange() { 
       this.uploading = true; 
       this.failed = false; 

       this.file = document.getElementById('video').files[0]; 

       this.store().then(() => { 
        var form = new FormData(); 

        form.append('video', this.file); 
        form.append('uid', this.uid); 

        this.$http.post('/upload', form, { 
         progress: (e) => { 
          if (e.lengthComputable) { 
           this.updateProgress(e) 
          } 
         } 
        }).then(() => { 
         this.uploadingComplete = true 
        },() => { 
         this.failed = true 
        }); 
       },() => { 
        this.failed = true 
       }) 
      }, 
      store() { 
       return this.$http.post('/videos', { 
        title: this.title, 
        description: this.description, 
        visibility: this.visibility, 
        extension: this.file.name.split('.').pop() 
       }).then((response) => { 
        this.uid = response.json().data.uid; 
       }); 
      }, 
      update() { 
       this.saveStatus = 'Saving changes.'; 

       return this.$http.put('/videos/' + this.uid, { 
        link: this.link, 
        title: this.title, 
        description: this.description, 
        visibility: this.visibility 
       }).then((response) => { 
        this.saveStatus = 'Changes saved.'; 

        setTimeout(() => { 
         this.saveStatus = null 
        }, 3000) 
       },() => { 
        this.saveStatus = 'Failed to save changes.'; 
       }); 
      }, 
      updateProgress(e) { 
       e.percent = (e.loaded/e.total) * 100; 
       this.fileProgress = e.percent; 
      }, 
      confirm(message) { 
       swal({ 
       title: message, 
       text: null, 
       type: "warning", 
       showCancelButton: true, 
       cancelButtonText: "Cancel", 
       cancelButtonColor: '#FFF', 
       confirmButtonColor: "#2E112D", 
       confirmButtonText: "Yes, delete" 
       }).then(function(){ 
        this.$data = initialState(); 
       }.bind(this), function(dismiss) { 
       // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer' 
       if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those 
       // ignore 
       } else { 
        throw dismiss; 
       } 
       }) 
      } 
     }, 
     ready() { 
      window.onbeforeunload =() => { 
       if (this.uploading && !this.uploadingComplete && !this.failed) { 
        this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!'); 
       } 
      } 
     } 
    } 
</script> 

ответ

0

Mozilla документация предполагает

window.onbeforeunload = function(e) { 
    var dialogText = 'Dialog text here'; 
    e.returnValue = dialogText; 
    return dialogText; 
}; 

, а также утверждает, что:

С 25 мая 2011 года, спецификации состояния HTML5, что вызовы В этом событии могут игнорироваться методы window.alert(), window.confirm() и window.prompt(). Дополнительную информацию см. В спецификации HTML5.

Source содержит много других подробностей относительно причин и ожиданий от современных браузеров.

This question похоже дубликат.

This answer предполагает, что, чтобы избежать странное поведение браузера вы должны установить обработчик только тогда, когда это, чтобы предотвратить что-то (то есть во время навигации прочь должен вызвать диалог подтверждения)

0

Но как я могу затем сделать его пребывание на на той же странице и предотвратить навигацию, прежде чем он подтвердит, что он хочет уйти?

Добавить return false;, чтобы остановить мероприятие.

if (this.uploading && !this.uploadingComplete && !this.failed) { 
     this.confirm("Are you sure you want to navigate away? Your video won't be uploaded if you do so!"); 
    return false; // <==== add this 
} 

return false; делает 3 отдельных вещи, если вы позвоните:

event.preventDefault(); - Он останавливает поведение браузеров по умолчанию.

event.stopPropagation(); - Это предотвращает распространение события (или «пузырение вверх») DOM.

Остановки callback Выполнение и возврат немедленно при вызове.

+0

Это также остановит плагин sweetalert от выполнения и покажет предупреждение браузера по умолчанию. – Marco

Смежные вопросы