HTML5 - 尝试使用源元素加载视频时检测错误类型

Jor*_*rge 7 javascript html5 html5-video

我发现在使用元素src标记加载视频时处理错误与使用<video>元素加载视频时处理错误之间存在一些差异<source>.

例如,如果我尝试使用元素的src标记加载未找到的视频流(HTTP 404)video,则会触发事件并且元素存储错误数据:

HTML

<video src="http://not.found.url"></video>
Run Code Online (Sandbox Code Playgroud)

JS

var video = document.querySelector('video');

video.addEventListener('error', function(evt) {
  console.log(evt.target.error); // Object
});
video.load();
Run Code Online (Sandbox Code Playgroud)

video元件存储MediaError在对象error:

error: {
  code: 4,
  message: 'MEDIA_ELEMENT_ERROR: Format error'
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用source元素加载相同的视频流时:

HTML

<video>
  <source src="http://not.found.url">
</video>
Run Code Online (Sandbox Code Playgroud)

JS

var video = document.querySelector('video');
var source = document.querySelector('source');

video.addEventListener('error', function(evt) {
  // This event is not triggered
  console.log(evt.target.error); // null
});

source.addEventListener('error', function(evt) {
  console.log(evt.target.error); // null
});

video.load();
Run Code Online (Sandbox Code Playgroud)

source元素的错误处理程序是捕获错误只有一个,但错误的数据不存储.无论是video元素,也不是source件储存错误对象,因此,我可以说一个错误已被触发,但我不能知道错误的类型.

我想使用该source元素,并能够检测错误的原因是否是无效的视频格式,404资源或任何其他原因.

那可能吗?

谢谢!

Sal*_*n A 8

抱歉,错误代码不会帮助您解决 HTTP 错误。但是,使用<source>元素时获取错误代码的正确方法如下:

<video class="video" autoplay controls>
    <source src="http://example.com/does-not-exist">
    <source src="http://example.com/corrupted-video">
    <source src="http://example.com/unsupported-video">
</video>
<script>
    var video = document.querySelector("video");
    var source = document.querySelector("source:last-child");
    // <source> elements are processed one by one until a usable source is found
    // if the last source failed then we know all sources failed

    video.addEventListener("error", function(e) {
        console.log("<video> error");
        console.log(e.target.error);
        // e.target would be the <video> element
        // e.target.error -- https://html.spec.whatwg.org/multipage/media.html#mediaerror
    });

    source.addEventListener("error", function(e) {
        console.log("<source> error");
        // e does not contain anything useful -- https://html.spec.whatwg.org/multipage/media.html#event-source-error
        // e.target would be the <source> element
        // e.target.parentNode would be the <video> element
        // e.target.parentNode.error -- https://html.spec.whatwg.org/multipage/media.html#mediaerror
        // e.target.parentNode.networkState -- https://html.spec.whatwg.org/multipage/media.html#dom-media-networkstate
        console.log(e.target.parentNode.error);
        console.log(e.target.parentNode.networkState);
    });
</script>
Run Code Online (Sandbox Code Playgroud)

虽然此方法不会告诉您有关 HTTP 错误的信息,但您可以通过以下方式获得一些额外信息:

  1. 检查错误是否由<source><video>
  2. 看着errornetworkState