如何在加载网页之前运行内容脚本?

2 google-chrome-extension google-chrome-devtools

我想更改一些 dom 内容,以便所有输入字段值都是""网页的,然后用户才能看到它。我该怎么做?有什么办法可以做到这一点吗?谢谢。

wOx*_*xOm 5

您需要一个在document_start上运行的内容脚本,以及以下两种方法之一:

  1. MutationObserver(文档),但它会减慢页面加载速度:
  2. 添加 CSS 样式覆盖以使 INPUT 文本透明,并在加载页面时清除元素并删除样式:

    清单.json:

    "content_scripts": [{
        "matches": ["<all_urls>"],
        "run_at": "document_start",
        "all_frames": true,
        "js": ["content.js"]
    }],
    
    Run Code Online (Sandbox Code Playgroud)

    内容.js:

    // document is empty now so we'll only add the style
    var style = document.documentElement.appendChild(document.createElement('style'));
    style.textContent = 'input {color: transparent !important;}';
    
    // once DOM is ready clear the inputs
    document.addEventListener('DOMContentLoaded', function() {
        var inputs = document.getElementsByTagName('input');
        for (var i = inputs.length; --i >= 0; ) {
            var input = inputs[i];
            if (input.value) {
                input.value = '';
            }
        }
        style.remove();
    });
    
    Run Code Online (Sandbox Code Playgroud)