素人がプログラミングを勉強していたブログ

プログラミング、セキュリティ、英語、Webなどのブログ since 2008

連絡先: すかいぷ:javascripter_  か javascripter あっと tsukkun.net skypeのほうがいいです

Greasemonkey用ユーティリティ関数(XPathとCSS Selectorの両方を受け取る関数、$nなど)

function Class()
  function () {
    if (typeof this.initalize == "function")
      return this.initalize.apply(this, arguments);
    }
function extend(base, ext) {
  for (var prop in ext)
    if (ext.hasOwnProperty(prop)) {
      var g = ext.__lookupGetter__(prop),
      s = ext.__lookupSetter__(prop);
      if (g) base.__defineGetter__(prop, g);
        else if (s) base.__defineSetter__(prop, s);
          else base[prop] = ext[prop];
    }
  return base;
}
function $a(arr) Array.slice(arr);
function $s(selector, context) $a((context || document).querySelectorAll(selector));
function $x(exp, context) {
  var xp = document.evaluate(exp, context || document, null, XPathResult.ORDERD_NODE_SNAPSHOT_TYPE, null),
  ret = [];
  for (var i = 0;i < xp.snapshotLength;i++) ret.push(xp.snapshotItem(i));
  return ret;
}
function $q(str, context) {
  var xpathExp = /^(?:\/|id\()/;
  if (xpathExp.test(str)) {
    try {
      return $x(str, context);
    } catch (e) {
      return $s(str, context);
    }
  }
  try {
    return $s(str, context);
  } catch (e) {
    return $x(str, context);
  }
}
function $n(name, attr, child, text, html) {
  if (typeof name == "object")
    var {name, attr, child, text, html} = name;
  var baseElem = document.createElement(name);
  if (attr) {
    for (var prop in attr)
      if (attr.hasOwnProperty(prop)) {
        if (prop == "style") {
          for(var cssProp in attr.style)
            if (attr.style.hasOwnProperty(cssProp))
              baseElem.style[cssProp] = attr.style[cssProp];
        } else {
          baseElem[prop] = attr[prop];
        }
      }
  }
  if (child) {
    var df = document.createDocumentFragment();
    child.forEach(df.appendChild, df);
    baseElem.appendChild(df);
  }
  if (text) baseElem.textContent = text;
  if (html) baseElem.innerHTML = html;
  return baseElem;
}
function log() {
  var c = unsafeWindow.console;
  if (typeof c != "undefined")
    c.log.apply(c, arguments);
    else GM_log.apply(this, arguments);
}