HTML5 video error handling

前端 未结 6 1129
一整个雨季
一整个雨季 2020-12-09 02:50

I need to tell, whether video cannot be played (\"x\" sign is shown in browser).

This code does\'t works. \"onerror\" event will never be fired under Firefox

6条回答
  •  佛祖请我去吃肉
    2020-12-09 03:36

    From Firefox 4 onwards, the 'error' event is dispatched on the element.

    And you should add an error handler on the only/last source:

    HTML

    
    

    JS

    var v = document.querySelector('video#vid');
    var sources = v.querySelectorAll('source');
    
    if (sources.length !== 0) {
        var lastSource = sources[sources.length-1];
    
        lastSource.addEventListener('error', function() {
            alert('uh oh');
        });
    }
    

    JQuery

    $('video source').last().on('error', function() {
        alert('uh oh');
    });
    

    AngularJS

    You can create an error handling directive (or just use ng-error):

    
    

    Where the error handling directive's link function should do (copied from ng-error):

    element.on('error', function(event) {
        scope.$apply(function() {
            fn(scope, {$event:event});
        });
    });
    

提交回复
热议问题