繁体   English   中英

InsertAdjacentHTML 被页面上的 HTML 覆盖

[英]InsertAdjacentHTML gets overridden by HTML on page

我正在创建一个浏览器扩展,当我点击任何网页上的文本时,我已经让它打开了一个模式。

我使用了insertAdjacentHTML并且出于某种原因,每当我单击打开模态时,它都会使用我所在的网页/网站的样式,而不是我在 CSS 文件中提供的样式。

我怎样才能让我的 CSS 被覆盖,以便我保持我的样式?

认为问题发生的地方:

// On mouse click
allText[i].addEventListener('click', async () => {
  // Load in HTML file
  fetch(chrome.runtime.getURL(findFontModal))
    .then(r => r.text())
    .then(html => {
      allText[i].insertAdjacentHTML('beforeend', html);
    });
});

完整的js代码:

// Receiving message from popup.js
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.switchStatus === "on") {
      // Getting all text elements
      const allText = document.querySelectorAll('h1, h2, h3, h4, h5, p, li, td, caption, span, a');
      const colors = ['#ffadad', '#ffd6a5', '#fdffb6', '#caffbf', '#bdb2ff', '#9fdfff'];
      const findFontModal = 'findfont.html'

      // Loop through all text elements-
      // to be able to manipulate each individual one
      for (let i = 0; i < allText.length; i++) {
        // On hover
        allText[i].addEventListener('mouseover', async () => {
          allText[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
          allText[i].style.cursor = "pointer";
        });

        allText[i].addEventListener('mouseout', async () => {
          allText[i].style.backgroundColor = null;
        });

        // On mouse click
        allText[i].addEventListener('click', async () => {
          // Load in HTML file
          fetch(chrome.runtime.getURL(findFontModal))
            .then(r => r.text())
            .then(html => {
              allText[i].insertAdjacentHTML('beforeend', html);
            });
        })
      }

      sendResponse({ status: "done" });
    }

    // When toggle switch is unchecked
    else if (request.switchStatus === "off") {
      const allText = document.querySelectorAll('h1, h2, h3, h4, h5, p, li, td, caption, span, a');
      for (let i = 0; i < allText.length; i++) {
        allText[i].style.backgroundColor = null;
      }

      sendResponse({ status: "done" });
    }
  }
);

模态 HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="content.css">
    <title>Find Font Modal</title>
</head>
<body>
    <div class="modal-div">
        <div class="titlebar">
            <i class="fas fa-times"></i>
        </div>

        <div class="main-content">
            <div class="names">
                <h1>Font Name</h1>
                <h5>Foundry Name</h5>
            </div>
            <div class="font-props">
                <div class="color-div">
                    <span class="dot"></span>
                    <h4>#000000</h4>
                </div>

                <div class="actual-props">
                    <div class="column-1">
                        <h4>Font Weight</h4>
                        <h3>Blank</h3>

                        <h4 class="second">Line Height</h4>
                        <h3>Blank</h3>
                    </div>

                    <div class="column-2">
                        <h4>Font Size</h4>
                        <h3>Blank</h3>
                    </div>
                </div>
            </div>

            <div class="buttons">
                <button class="tryfont-btn">Try out this font</button>
            </div>
        </div>
    </div>

    <script src="https://kit.fontawesome.com/7ad5f72cd3.js" crossorigin="anonymous"></script>
</body>
</html>

Github 上的代码: https : //github.com/JojoDuke/fs-extension-core

我相信原始问题中混淆的原因源于浏览器扩展如何将脚本和样式应用于浏览器选项卡的不同:

  • 脚本被沙箱化并拥有自己的内容脚本上下文,与当前加载在选项卡中的网页脚本隔离
  • 样式表与域的样式一起应用于页面:扩展样式可以重叠,覆盖页面样式,反之亦然。

这意味着当使用insertAdjacentHTML动态创建和附加元素到 DOM 时,网页的样式也将应用于这个新元素。

为了确保扩展样式 - 并且扩展样式 - 应用于元素,请使用 shadow DOM ,它将封装元素并将其样式与页面的其余部分隔离。 还要查看用于设置 shadow DOM 样式的选项。

这是我之前在浏览器扩展中使用的一个简化示例,用于演示此概念:

// create a container for the shadow DOM
// (or alternatively use some existing element in the DOM)
const container = document.createElement('div');
document.body.appendChild(container);
const shadow = container.attachShadow({mode: 'closed'});

// this elements will go inside the shadow DOM
// and it will have its own isolated style
const panel = document.createElement('div');
panel.style.position = "fixed";
panel.style.top=0;
panel.style.left=0;
panel.style.zIndex=2147483647;
panel.style.background="red";
panel.style.color="white";
panel.style.height = "100px";
panel.style.width = "250px";
panel.innerText="hello shadow world!";
shadow.appendChild(panel);

使用classesIDs所独有的分机。所有querySelectors您正在使用,和模态的HTML应该有类名和ID的所有可以说你的扩展名的前缀..

class="modal-div"会是这样的: class="_my_extension_modal-div"等等。 这样您就不会与任何网站的类/ID 重叠。


另一个技巧是将!important添加到您的 CSS 中,但这可能不起作用,或者在启用扩展程序的情况下查看实际网站时可能会阻止实际网站。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM