是否有一个与GreaseMonkey的TamperMonkey方法等价的GM_addStyle方法来添加CSS?
在GreaseMonkey中,您可以向多个元素添加一组CSS属性,如下所示:
GM_addStyle("body { color: white; background-color: black; } img { border: 0; }");要在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; }');这是可行的,但是是否有一个内置的GM_addStyle等价于TamperMonkey,这样我就不必在每个脚本上重复这个了?
发布于 2014-05-15 16:46:04
根据the TamperMonkey documentation的说法,它直接支持GM_addStyle,就像GreaseMonkey一样。检查包含/匹配规则是否正确,然后将此演示代码添加到用户脚本的顶部:
GM_addStyle('* { font-size: 99px !important; }');
console.log('ran');我刚刚在Chrome 35中的一个新的用户脚本上测试了它,它像预期的那样工作。如果您有任何其他 rule,您将需要为该函数添加一个,否则它将被检测并自动授予。
发布于 2015-10-16 18:03:49
4.0或+版本,2018年更新
ReferenceError: GM_addStyle is not defined您需要创建自己的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";
弃用
如果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; }");发布于 2017-09-18 18:07:39
如果有人被插入,我更改了代码,这样你就不必在每个css规则之后写“!重要”了。当然,只有当您使用函数而不是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);
}这个"addGlobalStyle('body { color: white; background-color: black; }');“的输出
将是"body { color: white !important; background-color: black !important; }');“
https://stackoverflow.com/questions/23683439
复制相似问题