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



我刚刚在使用<video>元素的src标签加载视频时发现了处理错误之间的某些差异,并使用<source>元素加载视频时。

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

html

<video src="http://not.found.url"></video>

JS

var video = document.querySelector('video');
video.addEventListener('error', function(evt) {
  console.log(evt.target.error); // Object
});
video.load();

video元素将MediaError对象存储在error中:

error: {
  code: 4,
  message: 'MEDIA_ELEMENT_ERROR: Format error'
}

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

html

<video>
  <source src="http://not.found.url">
</video>

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();

source元素错误处理程序是唯一捕获错误但错误数据的元素。video元素和source元素都存储一个错误对象,因此,我可以说触发了错误,但我无法知道该错误的类型。

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

可能吗?

谢谢!

对不起,但是错误代码不会帮助您解决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>

虽然这种方法没有告诉您有关HTTP错误的信息,但您可能可以通过以下方式获取一些额外信息。

  1. 检查错误是由<source>还是<video>
  2. 产生的错误
  3. 查看errornetworkState

最新更新