How do I prevent CSS interference in an injected piece of HTML?

前端 未结 3 1759
悲哀的现实
悲哀的现实 2021-01-05 22:43

I\'m currently developing a Safari extension that uses an injected script to further inject some HTML into the current webpage, as well as injecting some other scripts to ma

3条回答
  •  日久生厌
    2021-01-05 23:31

    You can't prevent that from happen. However, you can override the CSS rules. Give your main element a unique id (which really should be unique by obfustation, like "yourapplicationname_mainelement_name" or something), then override all possible styles that might give strange effects on your html.

    Your plugin:

    My paragraph that must not be styled

    Your css:

    #yourapplicationname_mainelement_name p {
      display: block;
      color: black;
      background: white;
      position: relative;
      ... and so on ...
    }
    

    As your css style rules are the most specific, given your id, they will override any settings present on the page where your html is injected.

    Further... It might be hard to see what rules are the most important. You can use firebug or similar to understand which is overriding another. You'll have a hard time without it when developing your application.

提交回复
热议问题