Search code examples
javascriptgoogle-chrome-extension

Chrome Extension: show additional content in an overlay


I have developed a Chrome extension that displays the definition and synonyms of a selected word on double-click. This additional content appears in a div that overlays the active page. I achieve this by appending a div, applying styles, and setting the z-index. Here are fragments to demonstrate my approach:

const tooltip = document.createElement("div");
tooltip.className = "extTooltip";
const styles = document.createElement("style");
styles.innerHTML = `...`
document.head.appendChild(styles);
document.body.appendChild(tooltip);

The issue is that some styles of my div are overridden by the page styles, despite my use of !important. I wonder if there is a more efficient way to achieve the desired behavior? style overridden, example 1 style overridden, example 2


Solution

  • You can use the all CSS rule to reset all rules for an element back to their inial values. From there you can apply your own styling as required.

    Here's a simplified working example using unset. You would need to investigate which of the possible values, initial, inherit, unset, revert or revert-layer, is best for your specific use case.

    div {
      background-color: #C00;
      color: #EEE;
    }
    
    #except-this {
      all: unset;
    }
    <div>Fizz</div>
    <div>Buzz</div>
    <div id="except-this">Foo</div>
    <div>Bar</div>