有些扩展程序会在 Chrome 的 Inspection 中显示为
#shadow-root(open)
. 的小页面弹出窗口
我想用Tampermonkey自定义它的样式,但是用
GM_addStyle(".class_name{zoom: 166%;}");
不行。它适用于原生元素。
GM_addStyle()
将它创建的 <style>
元素附加到 <head>
,因此它不能修改 Shadow DOM 元素的样式。你需要使用GM_addElement()
.
// ==UserScript==
// @name Shadow DOM styling
// @version 0.1
// @author double-beep
// @match http*://example.com
// @grant GM_addElement
// ==/UserScript==
(function() {
'use strict';
const shadowRoot = document.querySelector('element');
const styles = `div { color: red; }`;
GM_addElement(shadowRoot, 'style', { textContent: styles });
})();
如果未应用样式,您可以以类似的方式创建一个
<script>
元素:
GM_addElement(shadowRoot, 'script', {
textContent: 'shadowRootElement.shadowRoot.querySelector("...").style.color = "red";'
});
需要在shadow root中插入style标签
(从this answer中摘取一些代码)
function addStyleToShadowRoot(shadowRoot,css) {
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
shadowRoot.appendChild(style);
}
这样称呼它:
addStyleToShadowRoot(customElement.shadowRoot, myCss);