Commit 1d2eaf68 authored by Robert Knight's avatar Robert Knight

Switch to using `<link>` elements for stylesheets in shadow DOM

When Shadow DOM was first considered for use in the client `<link
rel="stylesheet">` was not widely supported as a way to load external styles into
shadow roots. This was resolved in the spec in https://github.com/whatwg/html/pull/1572
and has now long been supported by all browsers.

Using `<link>` simplifies the code and also avoids a possible problem with sites
that have a strict CSP policy that disallows inline styles. In the
browser extension context a `<link>` can still work in that scenario as long as the
stylesheet is loaded from a `chrome-extension://` URL.
parent ff5918d6
......@@ -10,20 +10,10 @@ function loadStyles(shadowRoot) {
return;
}
// Stylesheet <link> elements are inert inside shadow roots [1]. Until
// Shadow DOM implementations support external stylesheets [2], grab the
// relevant CSS files from the current page and `@import` them.
//
// [1] http://stackoverflow.com/questions/27746590
// [2] https://github.com/w3c/webcomponents/issues/530
//
// This will unfortunately break if the page blocks inline stylesheets via
// CSP, but that appears to be rare and if this happens, the user will still
// get a usable adder, albeit one that uses browser default styles for the
// toolbar.
const styleEl = document.createElement('style');
styleEl.textContent = `@import "${url}";`;
shadowRoot.appendChild(styleEl);
const linkEl = document.createElement('link');
linkEl.rel = 'stylesheet';
linkEl.href = url;
shadowRoot.appendChild(linkEl);
}
/**
......
......@@ -32,9 +32,9 @@ describe('annotator/util/shadow-root', () => {
it('injects stylesheets into the shadow root', () => {
createShadowRoot(container);
const styleEl = container.shadowRoot.querySelector('style');
assert.ok(styleEl);
assert.match(styleEl.textContent, /@import ".*annotator\.css.*"/);
const linkEl = container.shadowRoot.querySelector('link[rel=stylesheet]');
assert.ok(linkEl);
assert.include(linkEl.href, 'annotator.css');
});
it('applies the applyFocusVisiblePolyfill if exists', () => {
......@@ -52,8 +52,8 @@ describe('annotator/util/shadow-root', () => {
createShadowRoot(container);
const styleEl = container.shadowRoot.querySelector('style');
assert.isNull(styleEl);
const linkEl = container.shadowRoot.querySelector('link[rel=stylesheet]');
assert.isNull(linkEl);
link.setAttribute('rel', 'stylesheet');
});
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment