Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for iframe css injection #736

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
24 changes: 22 additions & 2 deletions src/css/inject-style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import * as postcss from 'postcss';
import { appendImportantToDeclarations } from './declaration';
import { getCssWithExpandedImports } from './import';

const getStylesheetId = (id: string) => {
return `stylebot-css-${id}`;
const getStylesheetId = (id: string, iframeIdx?: number) => {
return iframeIdx !== undefined
? `stylebot-css-${id}-iframe-${iframeIdx}`
: `stylebot-css-${id}`;
};

export const injectCSSIntoDocument = async (
Expand All @@ -12,6 +14,24 @@ export const injectCSSIntoDocument = async (
): Promise<void> => {
const cssWithExpandedImports = await getCssWithExpandedImports(css);

// inject CSS into all iframes
const iframeElems = document.getElementsByTagName('iframe');
for (const [iframeIdx, iframeElem] of Array.from(iframeElems).entries()) {
const iframeStylesheetId = getStylesheetId(id, iframeIdx);
const el = document.getElementById(iframeStylesheetId);
if (el) {
el.innerHTML = cssWithExpandedImports;
return;
}
const iframeDoc = (iframeElem as any).contentWindow.document;
const iframeStyle = iframeDoc.createElement('style');
iframeStyle.type = 'text/css';
iframeStyle.setAttribute('id', iframeStylesheetId);
iframeStyle.appendChild(iframeDoc.createTextNode(cssWithExpandedImports));
iframeDoc.head.appendChild(iframeStyle);
}

// then inject CSS into top document
const stylesheetId = getStylesheetId(id);
const el = document.getElementById(stylesheetId);

Expand Down
20 changes: 7 additions & 13 deletions src/inject-css/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,12 @@ const injectCss = (
};

const run = () => {
if (window === window.top) {
injectCss({
name: 'GetStylesForPage',
important: true,
});
} else {
injectCss({
name: 'GetStylesForIframe',
url: window.location.href,
important: true,
});
}
injectCss({
name: 'GetStylesForPage',
important: true,
});
};

run();
document.addEventListener('DOMContentLoaded', () => {
run();
});