How can I efficiently overwrite CSS with a content script?

后端 未结 2 563
情深已故
情深已故 2021-01-16 07:28

My problem is that I want to overwrite a style of a site. Thing is, there is a way to do this, using the !important sentence, as seen in this example.

H

相关标签:
2条回答
  • 2021-01-16 08:08

    The approach I've found easiest and most effective is to wrap whatever html template you're injecting in a div with a very specific id.

    <div id="my-specific-id">
      // Your injected HTML template or section of the website you want to change
    </div>
    

    Once you've done this, reset all of the CSS that might affect that section.

    #my-specific-id {
    
      // A comprehensive CSS reset
    
    }
    
    // The rest of your CSS will override the reset above
    

    Here is one such reset: http://html5doctor.com/html-5-reset-stylesheet/

    Note that you probably won't need everything from the CSS Reset, so remove what isn't relevant to take some load off the browser. I can't imagine that you really want to reset figcaption, for example.

    As someone writing an extension, you should care a lot about whether or not your extension ruins the user experience on websites you inject scripts into.

    The approach I've outlined will guarantee that only the sections of the website that you specifically care about are changed.

    You can do this with your own templates (say you wanted to add a weather widget to every page without using an iframe) or with specific parts of the page. You could, for example, wrap all <p> elements in a highly specific id that you define.

    Here's an example using Sass from a recent project I've been working on...

    #specific-id-css-ultimate-reset {
    html, button, input, div, p, img, form {
        margin: 0;
        padding: 0;
        border: 0;
        outline: 0;
        font-size: 100%;
        vertical-align: baseline;
        background: transparent;
    }
    
    @import "modules/all";
    @import "components/all";
    @import "popups/all";
    }
    
    <div id="my-superspecific-html-template-wrapper">
      <HTML TEMPLATE>
    </div>
    
    0 讨论(0)
  • 2021-01-16 08:20

    Maybe it will be faster for you to include all styles from the original CSS that you don't wish to override in your injected stylesheet? If so, you can then remove the original stylesheet from page using content script/code injection or blocking the browser request for CSS file.

    You can also write a small script that does some regex magic and adds !important to every line of given CSS file.

    0 讨论(0)
提交回复
热议问题