首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用userscript防止资源加载?

如何使用userscript防止资源加载?
EN

Stack Overflow用户
提问于 2022-08-03 15:19:33
回答 1查看 110关注 0票数 0

我正在尝试编写一个用户脚本,它可以用自定义内容替换网站的内容。但是在加载网站时,我的浏览器仍然下载不使用的js和css文件。而最初的内容仍然显示了一段时间。是否有更好的解决方案来防止这些资源的加载?

这是我的密码:

PS:事件beforescriptexecute只能在火狐中使用,我在MDN中发现了这一点。

代码语言:javascript
复制
// ==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>`;
});
EN

回答 1

Stack Overflow用户

发布于 2022-08-24 03:47:37

代码语言:javascript
复制
// ==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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73223817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档