Code snippets: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
No edit summary
Renamed xpath function to $x and cleaned it up a bit, added serialize/deserialize.
Line 1: Line 1:
= xpath helper =
= XPath helper =


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


Run a particular xpath expression <code>p</code> against the context node <code>context</code> (or the document, if not provided).
Run a particular xpath expression <code>p</code> against the context node <code>context</code> (or the document, if not provided).
Return the results as an array.
Return the results as an array.
= Serialize/deserialize =
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 ? 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

Revision as of 21:32, 23 March 2007

XPath helper

function $x(p, context) {
  if (!context) context = document;
  var arr = [];
  var 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;
}

Run a particular xpath expression p against the context node context (or the document, if not provided). Return the results as an array.

Serialize/deserialize

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 ? 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