Greasemonkey 笔记
Published on 星期六, 三月 18th, 2006
Dive Into Greasemonkey
Mark Pilgrim
Note:
- alert(’Hello world!’);
- anonymous function: window.setTimeout(function() { alert(’Hello world!’) }, 60);
- Tracking crashes with JavaScript Console
- Logging with GM_log(’hello’);
- if (/^http:\/\/diveintogreasemonkey\.org\//.test(window.location.href))
- Inspecting elements with DOM Inspector: see HTML element, attribute, and text node. CSS rules from each of the page’s stylesheets.
- Javascript Shell: Visit Jesse’s Web Development Bookmarklets http://www.squarefree.com/bookmarklets/webdevel.html>. 1.Drag the Shell bookmarklet to your links toolbar. 2. Visit a page (for example, Dive Into Greasemonkey http://diveintogreasemonkey.org/> home page), and click the Shell bookmarklet in your links toolbar. The Javascript Shell window will open in the background.
- Get properties of an element: props(element)
- Executing a user script on a domain and all its subdomains: // @include http://example.com/* // @include http://*.example.com/*
- Testing whether a Greasemonkey function is available: if (!GM_xmlhttpRequest)
- Testing whether a page includes an HTML element: var textareas = document.getElementsByTagName(’textarea’); if (textareas.length)
- Doing something for every HTML element: allElements = document.getElementsByTagName(‘*’); for (var i = 0; i
- Doing something for every element with a certain attribute: XPath: find all the elements that have an href attribut: allLinks = document.evaluate(’//a[@href]’, document, null,PathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i .snapshotItem(i);
- allDivs = document.evaluate(”//div[@class=’sponsoredlink’]”,
- Inserting content before an element: main = document.getElementById(’main’); newElement = document.createElement(’hr’); main.parentNode.insertBefore(newElement, main);
- Inserting content after an element: insertBefore(newElement, navbar.nextSibling);
- Remove: adSidebar.parentNode.removeChild(adSidebar);
- Replace: altText = document.createTextNode(theImage.alt); theImage.parentNode.replaceChild(altText, theImage);
- Inserting complex HTML quickly: var logo = document.createElement(”div”);
logo.innerHTML = ‘style=”margin: 0 auto 0 auto; ‘ + ‘border−bottom: 1px solid #000000; margin−bottom: 5px; ‘ + ‘font−size: small; background−color: #000000; ‘ + ‘color: #ffffff;”>‘ + ‘YOUR TEXT HERE ‘ + ‘
‘; document.body.insertBefore(logo, document.body.firstChild);
- Adding images without hitting a central server: var logo = document.createElement(’img’);
logo.src = ‘data:image/gif;base64,R0lGODlhDQAOAJEAANno6wBmZgAAAAAAACH5BAAAAAAA’+
‘LAAAAAANAA4AQAIjjI8Iyw3GhACSQecutsFV3nzgNi7SVEbo06lZa66LRib2UQAAOw%3D%3D’; - Adding CSS styles: 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(’p { font−size: large ! important; }’);
- Getting an element’s style: p1elem = document.getElementById(’p1′); p1style = getComputedStyle(p1elem, ”); alert(p1style.color);
- Setting an element’s style: logo.style.marginTop = ‘2em’;
- Post−processing a page after it renders: window.addEventListener(’load’,function() { document.body.innerHTML = newBody; },true);
- Matching case−insensitive attribute values: document.evaluate(”//form[translate(@method, ‘POST ‘, ‘post’)=’post’]”,
- Getting the current domain name: window.location.href, window.location.host
- Rewriting links: a.href.match(/\?/i)
- Redirecting pages: setting the window.location.href
- Intercepting user clicks: document.addEventListener(’click’, function(event) { // event.target is the element that was clicked
- Overriding a built−in Javascript method: HTMLFormElement.prototype.submit = newsubmit;
- GM_xmlhttpRequest({ method: ‘GET’, url: ‘http://greaseblog.blogspot.com/atom.xml’, headers: { ‘User−agent’: ‘Mozilla/4.0 (compatible) Greasemonkey/0.3′, ‘Accept’: ‘application/atom+xml,application/xml,text/xml’,},
onload: function(responseDetails) {var parser = new DOMParser(); var dom = parser.parseFromString(responseDetails.responseText, “application/xml”); var entries = dom.getElementsByTagName(’entry’); - Call function: if (doLoadAll) {doLoadAll();}
- addGlobalStyle(‘h1, h2, h3, h4 {’ +’ font−size: 12px ! important;’ +’ line−height: 14px ! important;’ +’ font−weight: normal ! important;’ +’}’ +’h1:hover, h2:hover, h3:hover, h4:hover {’ +’ background−color: inherit ! important;’ + ‘ color: inherit ! important;’ +’}');
- Open new window: a = links[i]; if (a.host && a.host != thisdomain) {a.target = “_blank”;
- String replacement based on regular expressions. replacements = {”\xa0″: ” “,”\xa9″: “(c)”}; regex = {}; for (key in replacements) {regex[key] = new RegExp(key, ‘g’);}textnodes = document.evaluate(”//text()”,..), s = textnode.data; textnodes.snapshotLength, for (key in replacements) {s = s.replace(regex[key], replacements[key]);}
- alt = img.alt.toUpperCase();
- Array: descriptions = new Array(); document.evaluate(”//label[@for=’” + a.name + “‘]”,…).singleNodeValue; descriptions.push(desc); descriptions.sort();
- configuration values are script−specific and can only be accessed by the user script that created them (regardless of the URL that the user script is currently running on). And unlike cookies, user script data are never transmitted to remote servers. GM_setValue(key, value); GM_getValue(key, defaultValue);
- Adding items to the menubar: appear in the User Script Commands submenu when the user script is active. GM_registerMenuCommand(menuText, callbackFunction);
- turn script into a full−fledged XPI with Greasemonkey compiler http://www.letitblog.com/greasemonkey−compiler/>. need visit GUID Generator http://extensions.roachfiend.com/cgi−bin/guid.pl> to generate a random GUID.
Link:
- Web: http://greasemonkey.mozdev.org
- Script repository: http://dunck.us/collab/GreaseMonkeyUserScripts
- tag: URIs http://taguri.org/>
- Inspect Element extension: Right−click on the element, From the context menu, select Inspect element. DOM Inspector should open with the H1 element already selected, and you can immediately start inspecting and/or editing its properties.
- Other debugging tools
-
- Web Developer Extension http://chrispederick.com/work/firefox/webdeveloper/> contains a plethora of functions for deconstructing pages.
- Aardvark http://www.karmatics.com/aardvark/> interactively displays tag names, id and class attributes.
- Venkman Javascript Debugger http://www.hacksrus.com/~ginda/venkman/> is a complete run−time Javascript debugger.
- Web Development Bookmarklets http://www.squarefree.com/bookmarklets/webdevel.html> contains a
number of useful functions you can drag to your toolbar. - JSUnit http://www.edwardh.com/jsunit/> is a unit testing framework for Javascript.
- js−lint http://www.crockford.com/javascript/lint.html> checks Javascript code for common errors.
- Mozilla XPath documentation http://www−jcsu.jesus.cam.ac.uk/~jg307/mozilla/xpath−tutorial.html> ·
XPath tutorial by example http://www.zvon.org/xxl/XPathTutorial/General/examples.html> ·
XPathResult reference http://www.xulplanet.com/references/objref/XPathResult.html> - http://adblock.mozdev.org/> and import an up−to−date filter list
- Use the data: URI kitchen http://software.hixie.ch/utilities/cgi/data/data> to construct your own data: URLs.
- CSS properties http://www.westciv.com/style_master/academy/css_tutorial/properties/>
- Extension Developer’s Extension http://ted.mielczarek.org/code/mozilla/extensiondev/> is invaluable for
debugging and testing Firefox extensions. - An .xpi file is really just a ZIP archive with a certain directory structure. You can use any ZIP program (such as 7−zip http://www.7−zip.org/> for Windows
Others:
- firefox −safe−mode