任意网站注入自定义 CSS 样式

1. 需求

能够自定义第三方网站的css样式,例如自定义第三方网站的背景,某个元素是否显示等

2. 下载油猴脚本,并设置

2.1. 添加油猴脚本,代码如下

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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// ==UserScript==
// @name Inject CSS
// @name:zh CSS 样式注入
// @namespace https://youthlin.com/
// @version 0.2
// @description Inject custom css to site.
// @description:zh 插入自定义 CSS 样式到任意网址
// @author Youth.霖
// @match *
// @include *
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addStyle
// @grant GM_registerMenuCommand
// ==/UserScript==
(function () {
'use strict';
// https://gist.github.com/youthlin/c4c08ffe4273ca7ebbf759289cef9964
const SETTING_KEY = 'cssMap'
const RAND = (Math.random() * 100000).toFixed(0)
const debug = function (...args) {
if (GM_getValue('debug', 'false') === 'true') {
console.log(...args)
}
}
const on = function (eventName, selector, handler) {
// http://youmightnotneedjquery.com/
document.addEventListener(eventName, function (e) {
// loop parent nodes from the target to the delegation node
for (let target = e.target; target && target !== this; target = target.parentNode) {
if (target.matches !== undefined && target.matches(selector)) {
handler.call(target, e);
break;
}
if (target.tagName === 'HTML') {
break;
}
}
}, false);
}
debug('Hello, Inject CSS.')

function start() {
const cssMap = cssValue()
const html = document.getElementsByTagName('html')[0]
const inject = `<div id="inject-watermark-${RAND}" class="inject-watermark"></div><style>
#inject-watermark-${RAND} {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 1;
pointer-events: none;
}
#inject-css-${RAND} {
display: none;
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 999;
background-color: rgba(0,0,0,.8);
justify-content: center;
align-items: center;
font-size: 16px;
}
#inject-css-setting {
max-height: 100%;
overflow: auto;
color: #000;
}
#inject-css-setting button {
border: 1px solid #ccc;
background-color: #fff;
cursor: pointer;
padding: .5em;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
#inject-css-setting table {
border-collapse: collapse;
background-color: #fff;
}
#inject-css-setting th, #inject-css-setting td {
border: 1px solid #ccc;
padding: .5em;
max-width: 50vw;
overflow: auto;
}
#inject-css-setting tr.active {
font-weight: bold;
}
#inject-css-setting td.active:after {
content: ' ⭐️';
}
#inject-css-setting tr:nth-child(even) {
background-color: #f2f2f2;
}
#inject-css-setting tr:hover {
background-color: #ddd;
}
#inject-css-setting .inject-css-delete,#inject-css-setting .inject-css-add {
width: 100%;
border-radius: 5px;
}
</style><div id="inject-css-${RAND}"></div>`
html.insertAdjacentHTML('beforeend', inject)
const wrapper = document.getElementById(`inject-css-${RAND}`)
GM_registerMenuCommand('Settings|设置', function (e) {
debug('Settings', e)
wrapper.style.display = 'flex'
}, 's')
render(cssMap, wrapper)
on('click', '.inject-css-delete', function (e) {
const deleteKey = e.target.dataset.key
cssMap.delete(deleteKey)
save(cssMap)
render(cssMap, wrapper)
})
on('click', '.inject-css-add', function (e) {
e.preventDefault()
const k = document.querySelector('#inject-css-url').value.trim()
const v = document.querySelector('#inject-css-value').value.trim()
if (k !== '' && v !== '') {
try {
new RegExp(k)
} catch (e) {
alert('`' + k + '`: 不是有效的正则表达式. error=' + e)
return
}
cssMap.set(k, v)
save(cssMap)
render(cssMap, wrapper)
}
})
on('click', '.inject-css-hide', function () {
wrapper.style.display = 'none'
})
on('keyup', 'html', function (e) {
if (e.code === 'Escape') {
wrapper.style.display = 'none'
}
}
)
document.querySelector('.inject-css-hide').click()
}

function cssValue() {
const settingValue = GM_getValue(SETTING_KEY, '{}');
debug('setting value:', settingValue)
let cssMap = JSON.parse(settingValue) // url regex -> css value
cssMap = new Map(Object.entries(cssMap)) // to Map
return cssMap
}

function save(cssMap) {
const s = JSON.stringify(Object.fromEntries(cssMap));// Map 需要先转为 Object 才能序列化为 JSON
GM_setValue(SETTING_KEY, s)
debug('saved', s, 'get:', cssValue())
}

function render(cssMap, wrapper) {
const url = window.location.href
debug('cssMap:', cssMap, 'url:', url)
// http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
let injectCss = ``
let tableBody = ''
for (const entry of cssMap) {
try {
let active = ''
if (new RegExp(entry[0]).test(url)) {
injectCss += entry[1] + "\n"
active = 'active'
}
tableBody += `<tr class="${active}"><td class="${active}"><code>${entry[0]}</code></td><td><pre>${entry[1]}</pre></td><td><button data-key="${entry[0]}" class="inject-css-delete">-</button></td></tr>`
} catch (e) {
debug('regexp error', e)
cssMap.delete(entry[0])
}
}
wrapper.innerHTML = `<style>${injectCss}</style><div id="inject-css-setting"><button class="inject-css-hide">关闭(Esc)</button>
<table><tbody><tr><th>URL 正则</th><th>注入 CSS</th><th>操作</th></tr>
${tableBody}
<tr><td><label><input type="text" id="inject-css-url" placeholder="点号斜线记得转义"></label></td>
<td><textarea id="inject-css-value" cols="30" rows="3" placeholder="html { background-color: #ccc; }"></textarea></td>
<td><button class="inject-css-add">+</button></td></tr>
</tbody></table></div>`
}

setTimeout(start, 2000)

})();


代码直达链接

2.2. 设置脚本

打开任意网站,点击油猴小图标,点击脚本的设置,如下图所示
![[Pasted image 20220918101207.png]]

设置匹配的网址,以及要注入的css样式,并点击操作列的“+”即可添加这一规则

![[Pasted image 20220918101445.png]]