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

前端 未结 3 1756
悲哀的现实
悲哀的现实 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:17

    that's a tough one. two options as I see it. You could set a wrapping div around all your content and prefix all your css with that. example:

    
      
    ...

    stylesheet:

    .wrappingDiv * {}
    

    Then when you inject jquery use that to close off the initial wrapping div before your content and to wrap any following content in the another wrapping div.

    Issues:

    1. Only possible if you are injecting other site content onto your own site.
    2. This could get complicated depending on where you are injecting html.

    The other option is to load a resetting stylesheet that targets your injected html specifically. In this case only your injected html would be wrapped but you'd need a css file that reset all attributes for all tags to their default before you add your own styles. No real issues here, just not very elegant...

    Another way would be to use an element that doesn't inherit stylesheet like an iframe, but that comes with its own issues...

提交回复
热议问题