Javascript:如何检查样式是否已注入

Javascript: How to check if a style is already injected

本文关键字:样式 是否 注入 检查 何检查 Javascript      更新时间:2023-09-26

在Chrome插件中,通过后台脚本,我以这种方式注入样式:

if(!styleLeft){
    var styleLeft = document.createElement("style");
    document.head.appendChild(styleLeft);
    styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
}

但是,当样式标记已在页面中时,if不起作用。如何寻找我的特定风格?

谢谢。

确保在此

检查的全局范围或任何外部范围内声明styleLeft。否则,您只需在范围结束时将其丢弃,并在每次迭代时创建一个新的空变量。

检查 ID。 示例:

if ( !!document.getElementById( 'a-long-id-that-will-never-collide' ) ) {
    var styleLeft = document.createElement("style");
    // Set the ID so that you can check for it later
    styleLeft.id = 'a-long-id-that-will-never-collide';
    document.head.appendChild(styleLeft);
    styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
}
你可以

解析document.styleSheets(它们应该可以在Chrome插件中访问,但我不是100%确定)。如果您为注入的每个样式指定一个唯一的标题,您将更容易找到已经注入的样式:

var styleLeft = document.createElement("style");
styleLeft.setAttribute("title", "<a unique id>");
document.head.appendChild(styleLeft);
styleLeft.innerHTML = "a, .left-hand { cursor: wait; }";
document.head.appendChild(styleLeft);

现在,document.styleSheets的最后一个条目具有 .title 属性。你可以用它来查看它是否是你的一个。