【问题标题】:How to prevent resource loading by using userscript?如何使用用户脚本防止资源加载?
【发布时间】:2022-08-24 11:47:37
【问题描述】:

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

这是我的代码:

PS:事件beforescriptexecute只能在Firefox中使用,我在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>`;
});

    标签: javascript userscripts


    【解决方案1】:
    // ==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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2016-08-06
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多