-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
83 lines (74 loc) · 2.12 KB
/
Copy pathindex.ts
File metadata and controls
83 lines (74 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* This content script injects any custom style for the page (if it exists)
* as soon as the document starts loading.
*/
import { injectCSSIntoDocument } from '@stylekit/css';
import { apply as applyReadability } from '@stylekit/readability';
import {
GetStylesForPage,
GetStylesForIframe,
GetStylesForPageResponse,
TabMessage,
} from '@stylekit/types';
const MAX_INJECT_COUNT = 10;
const INJECT_CSS_TIMEOUT = 300;
const injectCss = (
message: GetStylesForPage | GetStylesForIframe,
injectCount = 0
) => {
chrome.runtime.sendMessage(
message,
(response: GetStylesForPageResponse) => {
if (response) {
const { styles, defaultStyle } = response;
if (!response.userOriginApplied) {
styles.forEach(style => {
if (style.enabled) {
injectCSSIntoDocument(style.css, style.url).catch(e =>
console.warn('StyleKit: failed to inject CSS for', style.url, e)
);
}
});
}
if (defaultStyle && defaultStyle.readability) {
applyReadability();
}
} else if (injectCount < MAX_INJECT_COUNT) {
setTimeout(() => {
injectCss(message, injectCount + 1);
}, INJECT_CSS_TIMEOUT);
}
}
);
};
const run = () => {
if (window === window.top) {
injectCss({
name: 'GetStylesForPage',
preferUserOrigin: true,
});
} else {
injectCss({
name: 'GetStylesForIframe',
url: window.location.href,
parentUrl: document.referrer || undefined,
preferUserOrigin: true,
});
}
};
run();
chrome.runtime.onMessage.addListener((message: TabMessage) => {
if (message.name === 'PreviewStyle') {
const id = `stylekit-preview-${message.id}`;
let el = document.getElementById(id) as HTMLStyleElement | null;
if (!el) {
el = document.createElement('style');
el.id = id;
document.documentElement.appendChild(el);
}
el.textContent = message.css;
} else if (message.name === 'RemovePreviewStyle') {
const el = document.getElementById(`stylekit-preview-${message.id}`);
if (el) el.remove();
}
});