如何不在chrome扩展内容脚本中继承样式

mar*_*ark 5 css iframe google-chrome-extension

我正在编写一个Google Chrome扩展程序,可在每个页面上运行内容脚本.在我的内容脚本中,我在页面中注入了<div>一些<ul><li>子项.我在样式表中为这些元素指定了几种样式.

但我发现在一些随机页面上我的元素将继承网页上定义的样式,因为我没有为我的div指定每个样式属性.

什么是我可以阻止我注入的元素继承这些样式的最佳方法?

在我看来,我可以:

  • 指定样式表中的每一个样式(例如,通过查看没有干扰时计算出的样式),或者
  • 我可以把我的<div>内心<iframe>.但是,我必须在我的内容脚本的iframe和源页面之间传递hella消息,因为chrome://我的iframe src 的URL 和源页面的URL http://将被视为跨源.

yon*_*ran 1

我会选择第一个选择——完全指定您使用的元素的样式。但这比我想象的要复杂一些。

首先,您必须完全指定容器元素。然后,对于其后代,您必须说它们也应该使用默认值或从其父级继承(直到容器)。最后,您必须指定每个其他元素的外观,以便它们不都是普通的跨度。

相关的 API 是DOM Level 2 StylegetComputedStyle接口。您可以使用除和之外的所有值,这应该是默认值。您还需要下载默认样式表,例如Webkit 用户代理样式表。然后,您可以调用以下函数来创建可以注入到文档中的完整样式表。CSSStyleSheetwidthheightauto

请注意,当您将样式表插入目标文档时,您必须使容器选择器尽可能具体,因为网页可能会提供比您的规则具有更高特异性的规则。例如,在 中<html id=a><head id=b><style>#a #b * {weird overrides}</style></head>#a #b *具有比 中更高的特异性#yourId div。但我想这并不常见。

注意:由于某种原因,当我加载 CSS 时,Chrome 会给出错误“无法加载资源”,除非它已经存在于<link>当前文档中。因此,您也应该在调用此函数的页面中包含 html.css。

// CSS 2.1 inherited prpoerties
var inheritedProperties = [
    'azimuth', 'border-collapse', 'border-spacing', 'caption-side',
    'color', 'cursor', 'direction', 'elevation', 'empty-cells',
    'font-family', 'font-size', 'font-style', 'font-variant',
    'font-weight', 'font', 'letter-spacing', 'line-height',
    'list-style-image', 'list-style-position', 'list-style-type',
    'list-style', 'orphans', 'pitch-range', 'pitch', 'quotes',
    'richness', 'speak-header', 'speak-numeral', 'speak-punctuation',
    'speak', 'speech-rate', 'stress', 'text-align', 'text-indent',
    'text-transform', 'visibility', 'voice-family', 'volume',
    'white-space', 'widows', 'word-spacing'];
// CSS Text Level 3 properties that inherit http://www.w3.org/TR/css3-text/
inheritedProperties.push(
    'hanging-punctuation', 'line-break', 'punctuation-trim',
    'text-align-last', 'text-autospace', 'text-decoration-skip',
    'text-emphasis', 'text-emphasis-color', 'text-emphasis-position',
    'text-emphasis-style', 'text-justify', 'text-outline',
    'text-shadow', 'text-underline-position', 'text-wrap',
    'white-space-collapsing', 'word-break', 'word-wrap');
/**
 * Example usage:
       var fullStylesheet = completeStylesheet('#container', 'html.css').map(
           function(ruleInfo) {
               return ruleInfo.selectorText + ' {' + ruleInfo.cssText + '}';
           }).join('\n');
 * @param {string} containerSelector The most specific selector you can think
 *     of for the container element; e.g. #container. It had better be more
 *     specific than any other selector that might affect the elements inside.
 * @param {string=} defaultStylesheetLocation If specified, the location of the
 *     default stylesheet. Note that this script must be able to access that
 *     locatoin under same-origin policy.
 * @return {Array.<{selectorText: string, cssText: string}>} rules
 */
var completeStylesheet = function(containerSelector,
                                  defaultStylesheetLocation) {
  var rules = [];
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);  // initializes contentDocument
  try {
    var span = iframe.contentDocument.createElement('span');
    iframe.contentDocument.body.appendChild(span);
    /** @type {CSSStyleDeclaration} */
    var basicStyle = iframe.contentDocument.defaultView.getComputedStyle(span);
    var allPropertyValues = {};
    Array.prototype.forEach.call(basicStyle, function(property) {
      allPropertyValues[property] = basicStyle[property];
    });
    // Properties whose used value differs from computed value, and that
    // don't have a default value of 0, should stay at 'auto'.
    allPropertyValues['width'] = allPropertyValues['height'] = 'auto';
    var declarations = [];
    for (var property in allPropertyValues) {
      var declaration = property + ': ' + allPropertyValues[property] + ';';
      declarations.push(declaration);
    }
    // Initial values of all properties for the container element and
    // its descendants
    rules.push({selectorText: containerSelector + ', ' +
                              containerSelector + ' *',
                cssText: declarations.join(' ')});

    // For descendants, some of the properties should inherit instead
    // (mostly dealing with text).
    rules.push({selectorText: containerSelector + ' *',
                cssText: inheritedProperties.map(
                    function(property) {
                      return property + ': inherit;'
                    }).join(' ')});

    if (defaultStylesheetLocation) {
      var link = iframe.contentDocument.createElement('link');
      link.rel = 'stylesheet';
      link.href = defaultStylesheetLocation;
      iframe.contentDocument.head.appendChild(link);
      /** @type {CSSStyleSheet} */
      var sheet = link.sheet;
      Array.prototype.forEach.call(
          sheet.cssRules,
          /** @param {CSSStyleRule} cssRule */
          function(cssRule) {
        rules.push({
            selectorText: containerSelector + ' ' + cssRule.selectorText,
            cssText: cssRule.style.cssText});
      });
    }
    return rules;
  } finally {
    document.body.removeChild(iframe);
  }
};
Run Code Online (Sandbox Code Playgroud)