HTML5 视频错误处理

发布于 2024-10-30 09:02:41 字数 365 浏览 4 评论 0原文

我需要告诉,视频是否无法播放(浏览器中显示“x”符号)。

这段代码不起作用。 “onerror”事件在 Firefox 下永远不会被触发

var v = document.getElementsByTagName("video")[0];
    if ( v != undefined )
        v.onerror = function(e) {
            if ( v.networkState == v.NETWORK_NO_SOURCE )
            {
                // handle error
            }
        }

这里出了什么问题?

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

var v = document.getElementsByTagName("video")[0];
    if ( v != undefined )
        v.onerror = function(e) {
            if ( v.networkState == v.NETWORK_NO_SOURCE )
            {
                // handle error
            }
        }

What's wrong here ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

余生共白头 2024-11-06 09:02:41

“onerror”不是 的有效事件类型,

请改用“error”。

document.getElementsByTagName('video')[0].addEventListener('error', function(event) { ... }, true);

有关 事件的完整列表,请访问此处:https:// developer.mozilla.org/En/Using_audio_and_video_in_Firefox

"onerror" is not a valid event type for <video>

Use "error" instead.

document.getElementsByTagName('video')[0].addEventListener('error', function(event) { ... }, true);

For a complete list of events for <video> go here: https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox

記憶穿過時間隧道 2024-11-06 09:02:41

从 Firefox 4 开始,“error”事件调度于 元素

并且您应该在唯一/最后一个源上添加错误处理程序:

HTML

<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi"></source>
</video>

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

您可以创建错误处理指令(或者仅使用 ng-error):

<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi" ng-error="handleError()"></source>
</video>

错误处理指令的 link 函数应该执行的操作(从 ng-error 复制):

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

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

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

HTML

<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi"></source>
</video>

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):

<video id="vid" controls>
  <source src="dynamicsearch.mp4" type="video/mp4"></source>
  <source src="otherdynamicsearch.avi" type="video/avi" ng-error="handleError()"></source>
</video>

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});
    });
});
千秋岁 2024-11-06 09:02:41

很高兴知道 Chrome 和 Firefox 有不同的 onerror 回调。因此必须映射该错误。 Mozilla 使用 error.originalTarget

以下是有关如何使用纯 JavaScript 执行此操作的示例:

const file = 'https://samples.ffmpeg.org/MPEG-4/MPEGSolution_jurassic.mp4';

window.fetch(file, {mode: 'no-cors'})
.then((response) => response.blob())
.then((blob) => {
  const url = window.URL.createObjectURL(blob);
  const video = document.createElement('video');      

  video.addEventListener('error', (event) => {
    let error = event;

    // Chrome v60
    if (event.path && event.path[0]) {
      error = event.path[0].error;
    }

    // Firefox v55
    if (event.originalTarget) {
      error = error.originalTarget.error;
    }

    // Here comes the error message
    alert(`Video error: ${error.message}`);

    window.URL.revokeObjectURL(url);
  }, true);

  video.src = url;
  document.body.appendChild(video);
});

上面的示例将传入错误事件映射到 MediaError ,它可以用于显示错误播放消息。

It's good to know that Chrome and Firefox have different onerror callbacks. The error must therefore be mapped. Mozilla uses error.originalTarget.

Here is a sample on how to do it with pure JavaScript:

const file = 'https://samples.ffmpeg.org/MPEG-4/MPEGSolution_jurassic.mp4';

window.fetch(file, {mode: 'no-cors'})
.then((response) => response.blob())
.then((blob) => {
  const url = window.URL.createObjectURL(blob);
  const video = document.createElement('video');      

  video.addEventListener('error', (event) => {
    let error = event;

    // Chrome v60
    if (event.path && event.path[0]) {
      error = event.path[0].error;
    }

    // Firefox v55
    if (event.originalTarget) {
      error = error.originalTarget.error;
    }

    // Here comes the error message
    alert(`Video error: ${error.message}`);

    window.URL.revokeObjectURL(url);
  }, true);

  video.src = url;
  document.body.appendChild(video);
});

The above example maps an incoming error event into a MediaError which can be used to display an error playback message.

情话墙 2024-11-06 09:02:41

要捕获错误事件,您应该使用 video.addEventListener()

var video = document.createElement('video');
var onError = function() { // your handler};
video.addEventListener('error', onError, true);
...
// remove listener eventually
video.removeEventListener('error', onError, true);

请注意,addEventListener 的第三个参数(捕获时)应设置为 true。错误事件通常由视频元素(标签)的后代触发。

无论如何,依靠视频标签来触发 error 事件并不是检测视频是否已播放的最佳策略。此事件不会在某些 Android 和 iOS 设备上触发。

我能想到的最可靠的方法是监听 timeupdateending 事件。如果视频正在播放,您将至少收到 3 个 timeupdate 事件。如果发生错误,end 会比 error 更可靠地被触发。

To catch error event, you should use video.addEventListener():

var video = document.createElement('video');
var onError = function() { // your handler};
video.addEventListener('error', onError, true);
...
// remove listener eventually
video.removeEventListener('error', onError, true);

Note that the 3rd parameter of addEventListener (on capture) should be set to true. Error event is typically fired from descendants of video element ( tags).

Anyway, relying on video tag to fire an error event is not the best strategy to detect if video has played. This event is not fired on some android and iOS devices.

The most reliable method, I can think of, is to listen to timeupdate and ended events. If video was playing, you'll get at least 3 timeupdate events. In the case of error, ended will be triggered more reliably than error.

停滞 2024-11-06 09:02:41

尝试将事件侦听器添加到标签中 - 我认为 onerror 属性(“错误”事件)现在适用于源标签,而不是视频标签。

Try adding the event listener to the tag instead - I think the onerror attribute ("error" event) works on the source tag now, not the video tag.

我恋#小黄人 2024-11-06 09:02:41

哈巴狗的例子

video(src= encodeURI(item.urlVideo), type='video/mp4'  onerror="myFunction('param',this)")
script(src='/javascripts/onerror.js')

function myFunction(param, me) { 
    console.log(me);
    me.poster = './images/placeholder.jpg'; }

Pug example

video(src= encodeURI(item.urlVideo), type='video/mp4'  onerror="myFunction('param',this)")
script(src='/javascripts/onerror.js')

function myFunction(param, me) { 
    console.log(me);
    me.poster = './images/placeholder.jpg'; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文