O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Greasemonkey Hacks
By Mark Pilgrim
November 2005
More Info

HACK
#42
Make External Stylesheets Clickable
Ever want to see a page's stylesheets? Stop digging through source code to find them
The Code
[Discuss (0) | Link to this hack]

The Code

This user script runs on all web pages. It relies on the fact that Firefox maintains a global list of stylesheets, document.styleSheets (note the camelCase capitalization).

There is just one problem: if the page defines additional styles inline, such as with a <style> element in the <head> of the page, or in a style attribute on one specific element, Firefox creates a separate entry for each style in the document.styleSheets list, using the page's URL as the address of the stylesheet (which is technically true, but unhelpful for our purposes). As we loop through document.styleSheets, we need to check for this condition and filter out stylesheets that point back to the current page.

Save the following user script as showstylesheets.user.js:

	// ==UserScript==
	// @name		Show Stylesheets
	// @namespace	http://diveintomark.org/projects/greasemonkey/
	// @description adds links to all of page's stylesheets
	// @include		http://*
	// @include		https://*
	// ==/UserScript==

	var arHtmlStylesheetLinks = new Array();
	for (var i = document.styleSheets.length - 1; i >= 0; i--) {
		var oStylesheet = document.styleSheets[i];
		if (oStylesheet.href == location.href) continue;
		var ssMediaText = oStylesheet.media.mediaText;
		if (ssMediaText) {
				ssMediaText = 'media=&quot;' + ssMediaText + '&quot;';
		}
		arHtmlStylesheetLinks.push('<a title="' +
			ssMediaText + '" href="' +
			oStylesheet.href + '">' +
			oStylesheet.href.split('/').pop() + '</a>');
	}
	if (!arHtmlStylesheetLinks.length) return;
	var elmWrapperDiv = document.createElement('div');
	elmWrapperDiv.innerHTML = 'Stylesheets: ' +
		arHtmlStylesheetLinks.join(' &middot; ');
	elmWrapperDiv.style.textAlign = 'center';
	elmWrapperDiv.style.fontSize = 'small';
	elmWrapperDiv.style.fontFamily = 'sans-serif';
	document.body.insertBefore(elmWrapperDiv, document.body.firstChild);


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.