Me gustaría ir con la primera opción - para especificar completamente el estilo de los elementos que utiliza. Pero esto es un poco más complicado de lo que pensaba.
Primero, debe especificar completamente el elemento del contenedor. Luego, para sus descendientes, debe decir que también deben usar los valores predeterminados o heredar de sus padres (hasta el contenedor). Finalmente, debe especificar el aspecto de todos los demás elementos para que no sean todos los tramos simples.
Las API relevantes son getComputedStyle
y la interfaz CSSStyleSheet
de DOM Level 2 Style. Puede usar todos los valores excepto width
y height
, que deben ser auto
de forma predeterminada. También debe descargar una hoja de estilo predeterminada, como Webkit user agent stylesheet. Luego puede llamar a la siguiente función para crear una hoja de estilo completa que pueda insertar en el documento.
Tenga en cuenta que cuando inserte la hoja de estilo en el documento de destino, tendrá que hacer que el selector de contenedor sea lo más específico posible porque la página web podría dar reglas que tengan un specificity superior a sus reglas. Por ejemplo, en <html id=a><head id=b><style>#a #b * {weird overrides}</style></head>
, #a #b *
tiene una especificidad mayor que #yourId div
. Pero me imagino que esto no es común.
Nota: por alguna razón, Chrome me está dando el error "Error al cargar el recurso" cuando cargo el CSS, a menos que ya esté en un <link>
del documento actual. Entonces debería incluir html.css en la página que llama a esta función también.
// 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);
}
};
Técnicamente, hay una tercera ruta: [Shadow DOM] (http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/). Pero no conozco un ejemplo completo de trabajo para una extensión de Chrome. Hay una extensión [display-anchors] (https://github.com/Rob--W/display-anchors) que lo usa, pero no es una GUI que se comunica con la extensión. – Xan
Cómo se carga el orden de los archivos css en la página. ¿Es como la primera página que se carga css y luego los archivos css de script de contenido? ¿o viceversa? –
las respuestas están desactualizadas ahora, puede usar 'all: initial;' en css now –