Code snippets: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
No edit summary
Line 196: Line 196:


= make an array persistent in globalStorage =
= make an array persistent in globalStorage =
  /**
    Makes an given Array persistent in the globalStorage Object. It will not work
    with arrays that get additional mutator functions after it was made persistent.
    @param {String} name - name of the property of this that is the Array
    @param {String} domain - domain parameter of globalStorage
    @param {Array{String, String, ...}} add_mutator - additional non standard (Javascript 1.7) functions
  */
  function makeArrayPersistent(_name, _domain, _add_mutator){
    //workaround for scripts that work on pages stored on file://
    var domain = _domain || ".localdomain";
    //if the array is not defined yet we define it and fill it
    //with values stored in globalStorage
    if(!this[_name]){
      var evalStr = String(globalStorage[domain][_name]);
      this[_name] = eval(evalStr);
    //if it is defined allready we store it in globalStorage
    }else{
      globalStorage[domain][_name] = uneval(this[_name]);
    }
    //Watch will intercept asignments to this[_name] and store the new array in
    //globalStorage. The original array in globalStorage is discarded.
    this.watch(_name, function(_prop, _oldVal, _newVal){
      globalStorage[domain][_name] = uneval(_newVal);
      return _newVal;
    });
    //see a few lines below
    ["push", "pop", "reverse", "shift", "sort", "splice", "unshift"].forEach(function(_f){
      makeMutatorFunctionGlobal(_f);
    });
    //you can supply additional functions that will be wrapped
    if(_add_mutator)
      _add_mutator.forEach(function(_f){
      makeMutatorFunctionGlobal(_f);
    });
    //member functions that alter the array itself are wrapped. The wrapper will
    //call the mutator function and store the altered array in globalStorage
    function makeMutatorFunctionGlobal(_f){
      this[_name][_f] = function(){
        var f = this[_name][_f];
        return function(){
          alert(f);
          f.apply(this, arguments);
          globalStorage[domain].trolls = uneval(this);
        }
      }();
    }
  }

Revision as of 02:46, 27 April 2007

Shortcut to document.getElementById

function $(id) {
  return document.getElementById(id);
}

Example usage:

$("header").innerHTML = "Halloa!";


XPath helper

Run a particular XPath expression p against the context node context (or the document, if not provided).

Returns the results as an array.

function $x(p, context) {
  if (!context) context = document;
  var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  for (i = 0; item = xpr.snapshotItem(i); i++) arr.push(item);
  return arr;
}

Example usage (with Array.forEach):

var i, paragraphs = $x("//p");
paragraphs.forEach(function(paragraph) {  // Loop over every paragraph
  paragraph.innerHTML = "Halloa!";
});

Serialize/deserialize for GM_getValue

Used to store and retrieve multiple values (typically as a serialized hash) in a single GM_getValue slot.

function deserialize(name, def) {
  return eval(GM_getValue(name, (def || '({})')));
}

function serialize(name, val) {
  GM_setValue(name, uneval(val));
}

Example usage:

var settings = {a: 1, b: 2, c: 3};
serialize('test', settings);
var _settings = deserialize('test');
// now "settings == _settings" should be true

Log only when debugging

function debug(message) {
  if (DEBUG) GM_log(message);
}

Example usage:

var DEBUG = true;

debug("Attempting to load wubbles...");
load_wubbles();

DOM node manipulation

Create element with attributes

Creates a new element with the given attribute list

function createElement(type, attributes) {
  var element = document.createElement(type);
  if(attributes != null) {
     for(var i = 0, l = attributes.length; i < l; i++) {
        element.setAttribute(attributes[i][0], attributes[i][1]);
     }
  }
  return element;
}

Example usage:

var link = createElement('link', [['rel', 'stylesheet'], ['type', 'text/css'], ['href', basedir + 'style.css']]);

Remove DOM node

function remove(element) {
    element.parentNode.removeChild(element);
}

Insert node after node

function insertAfter(newNode, node) {
  return node.parentNode.insertBefore(newNode, node.nextSibling);
}

This works because even if node is the last node, nextSibling returns null so insertBefore puts the new node at the end.

Example usage:

var link = document.getElementById("the_link");
var icon = document.createElement("img");
icon.src = "…";
insertAfter(icon, link);

Advanced createElement for creating hierarchies of elements

Creates an element with attributes as well as child elements with their own attributes and children. Function should be called with arguments in the form of the following hash (note that "child1", "child2" should be hashes of the same structure): createEl({n: nodename, a: {attr1: val, attr2: val}, c: [child1, child2], evl: {type: eventlistener_type, f: eventlistener_function, bubble: bool}}, appendTo)


function createEl(elObj, parent) {
  var el;
  if (typeof elObj == 'string') {
     el = document.createTextNode(elObj);
  }
  else {
     el = document.createElement(elObj.n);
     if (elObj.a) {
        attributes = elObj.a;
        for (var key in attributes) {
           if (key.charAt(0) == '@')
              el.setAttribute(key.substring(1), attributes[key]);
           else 
              el[key] = attributes[key];
        }
     }
     if (elObj.evl) {
        el.addEventListener(elObj.evl.type, elObj.evl.f, elObj.evl.bubble);
     }
     if (elObj.c) {
        elObj.c.forEach(function (v, i, a) { createEl(v, el); });
     }
  }
  if (parent)
     parent.appendChild(el);
  return el;
}


Example usage:

   createEl({n: 'ol', a: {'@class': 'some_list', '@id': 'my_list'}, c: [
   {n: 'li', a: {textContent: 'first point'}, evl: {type: 'click', f: function() {alert('first point');}, bubble: true}},
   {n: 'li', a: {textContent: 'second point'}},
   {n: 'li', a: {textContent: 'third point'}}
   ]}, document.body);


GET an URL with callback function

Retrieves url using HTTP GET, then calls the function cb with the response text as its single argument.

function get(url, cb) {
  GM_xmlhttpRequest({
    method: "GET",
     url: url,
     onload: function(xhr) { cb(xhr.responseText); }
  });
}

Example usage:

function inform(text) {
  alert("The HTML of the page: " + text);
}
 
get("http://www.google.com", inform);

RegExp escape string

Escapes regexp meta characters in a string.

function escapeRegexp(s) {
  return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
}

Example usage:

var re = new RegExp("^" + escapeRegexp("fo*bar") + "$");
"fo*bar".match(re);  // Matches
"foobar".match(re);  // Doesn't match

!important Style

Appends !important to each rule then adds the CSS to the page letting you override the default formatting.

 function addStyle(css) {
   GM_addStyle(css.replace(/;/g,' !important;'));
 }


Example usage:

 addStyle('a {text-decoration:none;}');

make an array persistent in globalStorage

 /**
   Makes an given Array persistent in the globalStorage Object. It will not work
   with arrays that get additional mutator functions after it was made persistent.
   @param {String} name - name of the property of this that is the Array
   @param {String} domain - domain parameter of globalStorage
   @param {Array{String, String, ...}} add_mutator - additional non standard (Javascript 1.7) functions
 */
 function makeArrayPersistent(_name, _domain, _add_mutator){
   //workaround for scripts that work on pages stored on file://
   var domain = _domain || ".localdomain";
   //if the array is not defined yet we define it and fill it
   //with values stored in globalStorage
   if(!this[_name]){
     var evalStr = String(globalStorage[domain][_name]);
     this[_name] = eval(evalStr);
   //if it is defined allready we store it in globalStorage
   }else{
     globalStorage[domain][_name] = uneval(this[_name]);
   }
   //Watch will intercept asignments to this[_name] and store the new array in
   //globalStorage. The original array in globalStorage is discarded.
   this.watch(_name, function(_prop, _oldVal, _newVal){
     globalStorage[domain][_name] = uneval(_newVal);
     return _newVal;
   });
   //see a few lines below
   ["push", "pop", "reverse", "shift", "sort", "splice", "unshift"].forEach(function(_f){
     makeMutatorFunctionGlobal(_f);
   });
   //you can supply additional functions that will be wrapped
   if(_add_mutator)
     _add_mutator.forEach(function(_f){
     makeMutatorFunctionGlobal(_f);
   });
   //member functions that alter the array itself are wrapped. The wrapper will
   //call the mutator function and store the altered array in globalStorage
   function makeMutatorFunctionGlobal(_f){
     this[_name][_f] = function(){
       var f = this[_name][_f];
       return function(){
         alert(f);
         f.apply(this, arguments);
         globalStorage[domain].trolls = uneval(this);
       }
     }();
   }
 }