如何防止注入的HTML片段中的CSS干扰? [英] How do I prevent CSS interference in an injected piece of HTML?

查看:380
本文介绍了如何防止注入的HTML片段中的CSS干扰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个Safari扩展,它使用注入的脚本将一些HTML进一步注入当前网页,并注入一些其他脚本以使其工作。这一切工作正常,但问题是,注入的HTML受到网页已经导入的CSS样式表的影响。例如,HTML在网页上看起来很完美(CSS样式相对较少),但是在StackOverflow.com上(这些样式按钮等)非常糟糕。

jQuery是在显示这个HTML时注入网页,所以我有这个可用。我尝试了各种各样的东西,包括遍历所有元素,并在它们中的每一个上调用 removeClass()都无济于事。我也尝试添加CSS重置类等,但似乎没有任何工作。



防止CSS干扰的最佳方法是什么我的HTML?

解决方案

您无法防止发生这种情况。但是,您可以覆盖CSS规则。给你的主要元素一个唯一的ID(这真的应该是obfustation唯一的,例如yourapplicationname_mainelement_name或其他),然后覆盖所有可能给你的html带来奇怪效果的样式。



您的插件:

 < div id =yourapplicationname_mainelement_name> 
< p>我的段落不能设为样式< / p>
< / div>

您的css:

  #yourapplicationname_mainelement_name p {
display:block;
颜色:黑色;
背景:白色;
职位:亲属;
...等等...
}

随着你的css风格的规则是最具体的,给你的id,他们将覆盖你的html注入页面上的任何设置。

更多......可能很难看出哪些规则是最重要的。你可以使用萤火虫或类似的东西来理解哪一个在重写另一个。开发你的应用程序时,你会很难得到它。


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 make it work. This is all working fine, but the issue is that the HTML that is injected gets affected by CSS stylesheets that the webpage has already imported. For example, the HTML looks perfect on Google.com (which has relatively little CSS styling), but awful on StackOverflow.com (which styles buttons etc).

jQuery is injected into the webpage at the time of this HTML being displayed, so I have that available. I've tried all kinds of things, including walking through all of the elements and calling removeClass() on each of them, to no avail. I've also tried to add "CSS reset" classes, etc, but nothing seems to be working.

What's the best way to go around preventing the CSS from interfering with my HTML?

解决方案

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:

<div id="yourapplicationname_mainelement_name">
  <p>My paragraph that must not be styled</p>
</div>

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.

这篇关于如何防止注入的HTML片段中的CSS干扰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆