我刚刚发现了使用src
元素的<video>
标记加载视频时处理错误与使用<source>
元素加载视频时处理错误之间的一些区别。
例如,如果我试图使用src
元素的video
标记加载一个找不到的视频流(HTTP404),就会触发一个事件,该元素存储错误数据:
<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
元素加载相同的视频流时:
<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资源或任何其他原因。
这有可能吗?
谢谢!
发布于 2017-11-30 12:20:18
对不起,但是错误码不会帮助您处理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错误,但是您可以通过以下方法获得一些额外的信息:
<source>
或<video>
生成错误error
和networkState
https://stackoverflow.com/questions/47557135
复制相似问题