-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
94 lines (77 loc) · 2.22 KB
/
content.js
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
84
85
86
87
88
89
90
91
92
93
94
// Toggle CSS
// Browser extension to quickly enable or disable CSS in the current tab.
// Author: Phanx <[email protected]> (https://phanx.net)
// Last updated: 2018-03-29
// This is free and unencumbered software released into the public domain.
let disabled = false
let observer
const t = (arg) => Array.prototype.slice.call(arg)
const $ = (sel) => t(document.querySelectorAll(sel))
const startObserver = () => {
if (!observer) observer = new MutationObserver(observerCallback)
observer.observe(document.body, { attributes: true, subtree: true })
}
const stopObserver = () => {
if (!observer) return
observer.disconnect()
}
const removeInlineCSS = (el) => {
const css = el.getAttribute("style")
const old = el.getAttribute("data-removed-css")
if (old && old !== css) {
const sep = old.trim().substr(-1) === ";" ? "" : ";"
el.setAttribute("data-removed-css", old + sep + css)
} else if (!old) {
el.setAttribute("data-removed-css", css)
}
el.removeAttribute("style")
}
const restoreInlineCSS = (el) => {
const css = el.getAttribute("data-removed-css")
if (css) {
el.setAttribute("style", css)
el.removeAttribute("data-removed-css")
}
}
const observerCallback = (mutations) => {
stopObserver()
mutations.forEach((mutation) => {
if (mutation.type === "attributes" && mutation.attributeName === "style") {
removeInlineCSS(mutation.target)
}
})
startObserver()
}
const disableCSS = () => {
if (disabled) return // already disabled
disabled = true
t(document.styleSheets).forEach(sheet => {
sheet.disabled = true
})
$("[style]").forEach(el => removeInlineCSS)
startObserver()
}
const enableCSS = () => {
if (!disabled) return // already enabled
disabled = false
stopObserver()
t(document.styleSheets).forEach(sheet => {
sheet.disabled = false
})
$("[data-removed-css]").forEach(el => restoreInlineCSS)
}
chrome.runtime.onMessage.addListener((message, sender, callback) => {
// console.log("page received message:", message)
const { action, tabId } = message
if (action === "toggle") {
if (disabled) {
enableCSS()
} else {
disableCSS()
}
const state = disabled ? "disabled" : "enabled"
const reply = { state, tabId }
// console.log("page sending message:", reply)
callback(reply)
}
})