Many of the GreaseMonkey users are not familiar with the very useful set of APIs it has to offer. These functions can help you, especially if you are using it for large projects.
I will show here a few of the more useful APIs to my taste, you can read the entire API reference in the product wiki.
Logging
- A very useful function is GM_log().
- It is used to print log messages into the JavaScript console.
Example:
GM_log("x="+x);
Storing data locally
- Use the functions GM_setValue(), GM_getValue(), GM deleteValue() and GM_listValues() to store and retract data on the client side.
- This data is located in the Firefox preferences mechanism.
Example:
var x = GM_getValue("x","default value"); GM_log("x="+x); GM_setValue("x","new value");
Adding menu commands
- Another cool option is being able to add commands to be triggered from Firefox menu.
- To do that use the function GM_registerMenuCommand().
- This adds a new item under “Tools->Greasemonkey->User Script Commands”
Example:
function menuItemClicked(){ alert("menuItemClicked"); } GM_registerMenuCommand("aviTest", menuItemClicked);
Ajax calls
- Use GM_xmlhttpRequest to make ajax calls very easily.
Example:
GM_xmlhttpRequest({ method: "GET", url: "http://www.example.net/", headers: { "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used. "Accept": "text/xml" // If not specified, browser defaults will be used. }, onload: function(response) { // Inject responseXML into existing Object if not present if (!response.responseXML) { response.responseXML = new DOMParser() .parseFromString(response.responseText, "text/xml"); } GM_log([ response.status, response.statusText, response.readyState, response.responseHeaders, response.responseText, response.finalUrl, response.responseXML ].join("\n")); } });