Firefox – How to get Firefox Greasemonkey script to use a local cascading stylesheet

cssfirefoxgreasemonkeyjavascript

What's the correct syntax to link to a CSS file in the same directory as a Greasemonkey JavaScript? I've tried the following but it doesn't work:

var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'example.css';
cssNode.media = 'screen';
cssNode.title = 'dynamicLoadedSheet';
document.getElementsByTagName("head")[0].appendChild(cssNode);

If I can get this to work, it would be a lot easier than encasing CSS changes in JavaScript.

Best Answer

This is easy with the @resource directive. Like so:

// ==UserScript==
// @name            _Use external CSS file
// @resource        YOUR_CSS  YOUR_CSS_File.css
// @grant           GM_addStyle
// @grant           GM_getResourceText
// ==/UserScript==

var cssTxt  = GM_getResourceText ("YOUR_CSS");

GM_addStyle (cssTxt);

With no path/url information, @resource looks for "YOUR_CSS_File.css" in the same directory.

Related Question