Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,8 @@ By default, the style-loader appends `<style>` elements to the end of the style
```

### `insertInto`
By default, the style-loader inserts the `<style>` elements into the `<head>` tag of the page. If you want the tags to be inserted somewhere else, e.g. into a [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot), you can specify a CSS selector for that element here, e.g
By default, the style-loader inserts the `<style>` elements into the `<head>` tag of the page. If you want the tags to be inserted somewhere else you can specify a CSS selector for that element here. If you target an [IFrame](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) make sure you have sufficient access rights, the styles will be injected into the content document head.
You can also insert the styles into a [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot), e.g

**webpack.config.js**
```js
Expand Down
14 changes: 12 additions & 2 deletions lib/addStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,19 @@ var getElement = (function (fn) {

return function(selector) {
if (typeof memo[selector] === "undefined") {
memo[selector] = fn.call(this, selector);
var styleTarget = fn.call(this, selector);
// Special case to return head of iframe instead of iframe itself
if (styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch(e) {
styleTarget = null;
}
}
memo[selector] = styleTarget;
}

return memo[selector]
};
})(function (target) {
Expand Down
12 changes: 12 additions & 0 deletions test/basicTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ describe("basic tests", function() {
"<div class='target'>",
checkValue,
"</div>",
"<iframe class='iframeTarget'/>",
"</body>",
"</html>"
].join("\n");
Expand Down Expand Up @@ -103,6 +104,17 @@ describe("basic tests", function() {
runCompilerTest(expected, done, undefined, selector);
}); // it insert into

it("insert into iframe", function(done) {
let selector = "iframe.iframeTarget";
styleLoaderOptions.insertInto = selector;

let expected = requiredStyle;

runCompilerTest(expected, done, function() {
return this.document.querySelector(selector).contentDocument.head.innerHTML;
}, selector);
}); // it insert into

it("singleton", function(done) {
// Setup
styleLoaderOptions.singleton = true;
Expand Down