TamperMonkey是否相当于GreaseMonkey GM_addStyle
添加CSS 的方法?
在GreaseMonkey中,您可以向多个元素添加一堆CSS属性,如下所示:
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");
Run Code Online (Sandbox Code Playgroud)
要在TamperMonkey中执行等效操作,我现在必须执行以下操作:
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css;
head.appendChild(style);
}
addGlobalStyle('body { color: white; background-color: black; }');
Run Code Online (Sandbox Code Playgroud)
这有效,但GM_addStyle
TamperMonkey 是否有内置的等价物,这使我不必在每个脚本上重复这个?
A-3*_*312 70
ReferenceError: GM_addStyle is not defined
Run Code Online (Sandbox Code Playgroud)
您需要创建自己的GM_addStyle函数,如下所示:
// ==UserScript==
// @name Example
// @description Usercript with GM_addStyle method.
// ==/UserScript==
function GM_addStyle(css) {
const style = document.getElementById("GM_addStyleBy8626") || (function() {
const style = document.createElement('style');
style.type = 'text/css';
style.id = "GM_addStyleBy8626";
document.head.appendChild(style);
return style;
})();
const sheet = style.sheet;
sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}
//demo :
GM_addStyle("p { color:red; }");
GM_addStyle("p { text-decoration:underline; }");
document.body.innerHTML = "<p>I used GM_addStyle.</p><pre></pre>";
const sheet = document.getElementById("GM_addStyleBy8626").sheet,
rules = (sheet.rules || sheet.cssRules);
for (let i=0; i<rules.length; i++)
document.querySelector("pre").innerHTML += rules[i].cssText + "\n";
Run Code Online (Sandbox Code Playgroud)
如果GM_addStyle(...)
不起作用,请检查您是否有@grant GM_addStyle
标题.
像这样 :
// ==UserScript==
// @name Example
// @description See usercript with grant header.
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");
Run Code Online (Sandbox Code Playgroud)
lpd*_*lpd 29
根据TamperMonkey文档,它GM_addStyle
直接支持,如GreaseMonkey.检查您的包含/匹配规则是否正确,然后将此演示代码添加到用户脚本的顶部:
GM_addStyle('* { font-size: 99px !important; }');
console.log('ran');
Run Code Online (Sandbox Code Playgroud)
我刚刚在Chrome 35中使用新用户测试它,它按预期工作.如果您有任何其他@grant
规则,则需要为此功能添加一个规则,否则应自动检测并授予该规则.
小智 5
如果有人对我感兴趣,我会更改代码,这样您就不必在每个CSS规则后都写“!important”。当然,仅当您使用函数而不是GM_addStyle时,这才有效。
function addGlobalStyle(css) {
var head, style;
head = document.getElementsByTagName('head')[0];
if (!head) { return; }
style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = css.replace(/;/g, ' !important;');
head.appendChild(style);
}
Run Code Online (Sandbox Code Playgroud)
此“ addGlobalStyle('body { color: white; background-color: black; }');
” 的输出,
将是“ body { color: white !important; background-color: black !important; }');
”