簡體   English   中英

Chrome擴展程序:使用JavaScript刪除所有樣式

[英]Chrome Extension: Removing all styles using Javascript

我當然對此有些陌生。 我對HTML / CSS的了解比對Javascript的了解還要多。 我知道足夠編寫擴展程序的代碼,但是我遇到了可能是Chrome特有的問題。 我不想太具體,但是作為擴展程序的一部分,我想從所有網頁中刪除樣式。

這是我所擁有的:

manifest.json

{
"manifest_version": 2,
    "name": "[redacted]",
    "description": "[redacted]",
    "version": "1.0",
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["script.js"],
                "run_at": "document_start"
        }
    ]
}

script.js

function lolxd() {
    var hs = document.getElementsByTagName('style');
    for (var i=0, max = hs.length; i < max; i++) {
        hs[i].parentNode.removeChild(hs[i]);
}

window.onload = lolxd();

我嘗試了多種不同的腳本,但沒有一個起作用。 奇怪的是,擴展程序可以很好地加載,但是Javascript無法正常運行,我仍然可以在所有網頁上看到樣式。 有什么幫助嗎?

像這樣:

function removeCSS() {
    // remove `link`
    var links = document.getElementsByTagName('link');
    for(var i = 0, len = links.length; i < len; i++) {
        links[i].parentNode.removeChild(links[i]);
    }

    // remove `style`
    var styles = document.getElementsByTagName('style');
    for(var j = 0, len = styles.length; j < len; j++) {
        styles[j].parentNode.removeChild(styles[j]);
    }

    // remove inline style
    var nodes = document.querySelectorAll('[style]');
    for(var h = 0, len = nodes.length; h < len; h++) {
        nodes[h].removeAttribute('style');
    }
}

您可以遞歸地遍歷所有元素,並刪除樣式屬性,刪除所有鏈接的(外部)樣式表和嵌入式樣式表。

之前

 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://www.w3schools.com/html/styles.css"> <style> p { font-size: 150%; } </style> </head> <body> <h1>This is a heading</h1> <p style="font-weight: bold;">This is a paragraph.</p> </body> </html> 

 function removeStyles(el) { // code to remove inline styles el.removeAttribute('style'); if (el.childNodes.length > 0) { for (var child in el.childNodes) { /* filter element nodes only */ if (el.childNodes[child].nodeType == 1) removeStyles(el.childNodes[child]); } } // code to remove embedded style sheets var styletag = document.getElementsByTagName('style'); var i = 0; for (; i < styletag.length; i++) { styletag[i].remove(); } // code to remove external stylesheets var stylesheets = document.getElementsByTagName('link'), sheet; for (i = 0; i < stylesheets.length; i++) { sheet = stylesheets[i]; if (sheet.getAttribute('rel').toLowerCase() == 'stylesheet') sheet.parentNode.removeChild(sheet); } } removeStyles(document.body); 
 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://www.w3schools.com/html/styles.css"> <style> p { font-size: 150%; } </style> </head> <body> <h1>This is a heading</h1> <p style="font-weight: bold;">This is a paragraph.</p> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM