我正在尝试编写一个用户脚本,它可以用自定义内容替换网站的内容。但是在加载网站时,我的浏览器仍然下载不使用的js和css文件。而最初的内容仍然显示了一段时间。是否有更好的解决方案来防止这些资源的加载?
这是我的密码:
PS:事件beforescriptexecute只能在火狐中使用,我在MDN中发现了这一点。
// ==UserScript==
// @name New script - example.com
// @match https://example.com/
// @grant none
// @run-at document-start
// ==/UserScript==
const obs = new MutationObserver((mutationsList, observer) => {
for (let mut of mutationsList) {
for (let node of mut.addedNodes) {
if (node.tagName === 'SCRIPT') {
node.addEventListener('beforescriptexecute', (e) => { // Bad
e.preventDefault();
});
node.parentElement.removeChild(node);
}
}
}
});
obs.observe(document.documentElement, { attributes: false, childList: true, subtree: true });
document.addEventListener('DOMContentLoaded', (e) => {
obs.disconnect();
document.head.innerHTML = '';
document.body.innerHTML = `<p>Hello World</p>`;
});发布于 2022-08-24 03:47:37
// ==UserScript==
// @name New script - example.com
// @namespace Violentmonkey Scripts
// @match https://example.com/
// @grant none
// @version 1.0
// @run-at document-start
// ==/UserScript==
const obs = new MutationObserver((mutationsList) => {
for (const mut of mutationsList) {
for (const node of mut.addedNodes) {
if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE') {
// console.log(node);
node.remove();
}
}
}
});
obs.observe(document.documentElement, { childList: true, subtree: true });
function clearHeadAndBody() {
document.head.innerHTML = '';
document.body.innerHTML = `<p>Hello World</p>`;
setTimeout(() => {
obs.disconnect();
}, 1000);
}
if (document.readyState !== 'loading') {
/**
* Sometimes, the page is done loading before the script is
* injected, usually when reloading the page. In this case
* we run the code from here.
*/
clearHeadAndBody();
} else {
document.addEventListener('DOMContentLoaded', clearHeadAndBody);
}https://stackoverflow.com/questions/73223817
复制相似问题