Here is the solution used by https://userstyles.org, for example when you click on the link "Install style as userscript" on a style page like https://userstyles.org/styles/23516/midnight-surfing-global-dark-style:
if (typeof GM_addStyle != "undefined") {
GM_addStyle(css);
} else if (typeof PRO_addStyle != "undefined") {
PRO_addStyle(css);
} else if (typeof addStyle != "undefined") {
addStyle(css);
} else {
var node = document.createElement("style");
node.type = "text/css";
node.appendChild(document.createTextNode(css));
var heads = document.getElementsByTagName("head");
if (heads.length > 0) {
heads[0].appendChild(node);
} else {
// no head yet, stick it whereever
document.documentElement.appendChild(node);
}
}
Note: the code will work on Greasemonkey 4 as well as similar addons. I don't use Tampermonkey which is not open source but this answer may help other users finding this question. It will try to use several built-in functions of different addons before using a pure JavaScript solution. You may only need the code from the else block.
The "if" condition checking the head tag length may not be needed if you are sure the page has a head tag and you can add the node to the head like this instead : document.head.appendChild(node);
. However I noticed sometimes there is a JavaScript error saying the head is undefined or null depending on the method used, for example on facebook.com while logged out (at least when using // @run-at document-start
which is required for a dark theme to avoid flickering). So checking the length can be useful in this case.
If you want to use multiple lines of CSS code, you can create the css variable with backticks like this:
var css = `
CODE HERE
`;
Update: I just saw this solution is also used in another answer but there was no source mentioned. However you may see the console error document.documentElement is null
but it can be solved with a MutationObserver
workaround: https://github.com/greasemonkey/greasemonkey/issues/2996#issuecomment-906608348.
GM_
prefix. They should work on better PageRank of that documentation .. currently invisible on google.com/search?q=tampermonkey+gm_addstyle - Thanks! – Belen