How to really isolate stylesheets in the Google Chrome extension?

前端 未结 5 1643
滥情空心
滥情空心 2020-11-22 13:27

I wrote a Google Chrome extension, which popups a dialog with an autocomplete field and it\'s own style, but there are some sites where my CSS gets totally broken, which doe

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 13:50

    Either use all

    .some-selector {
        all: initial;
    }
    
    .some-selector * {
        all: unset;
    }
    

    or use Shadow DOM

    Library

    function Widget(nodeName, appendTo){
      this.outer = document.createElement(nodeName || 'DIV');
      this.outer.className = 'extension-widget-' + chrome.runtime.id;
      this.inner = this.outer.createShadowRoot();
      (appendTo || document.body).appendChild(this.outer);
    }
    
    Widget.prototype.show = function(){
      this.outer.style.display = 'block';
      return this;
    };
    
    Widget.prototype.hide = function(){
      this.outer.style.display = 'none';
      return this;
    };
    

    Usage

    var myWidget = new Widget();
    myWidget.inner.innerHTML = '

    myWidget

    ';

    You can access the widget contents via myWidget.inner and the outer via myWidget.outer.

    Styles

    /* 
     * Reset Widget Wrapper Element 
     */
    .extension-widget-__MSG_@@extension_id__ {
      background: none;
      border: none;
      bottom: auto;
      box-shadow: none;
      color: black;
      cursor: auto;
      display: inline;
      float: none;
      font-family : "Helvetica Neue", "Helvetica", "Arial", sans-serif;
      font-size: inherit;
      font-style: normal;
      font-variant: normal;
      font-weight: normal;
      height: auto;
      left: auto;
      letter-spacing: 0;
      line-height: 100%;
      margin: 0;
      max-height: none;
      max-width: none;
      min-height: 0;
      min-width: 0;
      opacity: 1;
      padding: 0;
      position: static;
      right: auto;
      text-align: left;
      text-decoration: none;
      text-indent: 0;
      text-shadow: none;
      text-transform: none;
      top: auto;
      vertical-align: baseline;
      white-space: normal;
      width: auto;
      z-index: 2147483648;
    }
    
    /* 
     * Add your own styles here 
     * but always prefix them with:
     * 
     *   .extension-widget-__MSG_@@extension_id__ 
     *   
     */
    
    .extension-widget-__MSG_@@extension_id__{
      position: fixed;
      top: 100px;
      margin: 0 auto;
      left: 0;
      right: 0;
      width: 500px;
    }
    
    .extension-widget-__MSG_@@extension_id__::shadow h1 {
      display: block;
      margin: 0 auto;
      padding: 20px;
      background-color: yellow;
      border: 10px solid green;
      font-size: 20px;
      text-align: center;
    }
    

提交回复
热议问题