我用 JavaScript 为 Chrome 编写了一个用户脚本扩展,以防止视频和音频标签在页面加载时自动下载
这是代码:
var videoTags = document.getElementsByTagName("Video");
var i;
for(i=0; i<videoTags.length; i++)
{
videoTags[i].setAttribute("preload", "none");
videoTags[i].removeAttribute("autoplay");
}
var audioTags = document.getElementsByTagName("audio");
var i;
for(i=0; i<audioTags.length; i++)
{
audioTags[i].setAttribute("preload", "none");
audioTags[i].removeAttribute("autoplay");
}
这是 manifest.json 文件:
{
"content_scripts": [ {
"exclude_globs": [ ],
"exclude_matches": [ ],
"include_globs": [ "*" ],
"js": [ "script.js" ],
"matches": [ "http://*/*", "https://*/*" ],
"run_at": "document_start"
} ],
"converted_from_user_script": true,
"description": "",
"key": "an2xaeZJluPfnpmcsHPXI4aajQPL1cBm5C2kKjaQwXA=",
"name": "test.user.js",
"version": "1.0"
}
问题是我的脚本会在片刻之后运行,直到浏览器 (Chrome) 下载视频/音频文件的一部分。
最佳答案
一个似乎可行的肮脏解决方案是使用 MutationObserver
从您的用户脚本,一旦您确定它确实在文档开始时运行。
这个 TamperMonkey 脚本对我有用:
// ==UserScript==
// @name Block videos preloading
// @include *
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var nodes = mutation.addedNodes;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeName == "VIDEO") {
nodes[i].setAttribute('preload', 'none');
nodes[i].removeAttribute('autoplay');
}
}
})
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
})();
如果您不希望脚本随后插入其他视频元素,您可能需要在 DOMContentLoaded
上调用 observer.disconnect()
。
关于javascript - 如何防止浏览器预加载 <video> 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37904871/