VimperatorでGreasemonkeyみたいな事をする

2010/02/09修正: Google検索のやつをFirefox 4.0b11でも動くようにした

特定のウェブページにちょっとしたユーザスクリプトを当てたい事があるけど、グリモンに追加するほどのものでもないし、さくっとVimpだけでやりたい時がある。Vimpにはそもそもautocmdコマンドがあるのでこれを使えばいいけど、ちょっと面倒。と言うわけで簡単なユーティリティ関数を書いた。

// Greasemonkeyライクなautocmdユーティリティ
// window, unsafeWindowの代わりにcontent, unsafeContent
function vimpMonkey(urlRegexPattern, func) {
  var cmd = eval('(function(args) {' +
    'var content = tabs.getTab(args.tab - 1).linkedBrowser.contentWindow;' +
    'var unsafeContent = content.wrappedJSObject;' +
    func.toSource() + '();' +
  '})');
  autocommands.add('PageLoad', urlRegexPattern, cmd);
}

ほぼautocmdで呼ばれる関数のラッパ関数なので、グリモンみたいなGM_なんとか関数はもちろん無い。windowは最上位のchromeウィンドウ(?)のままなので、コンテンツウィンドウにアクセスする時は変数contentを使う。また、unsafeWindowの代わりにunsafeContentを用意してある。

使い方は次のように。

// Google検索の左メニューを常に表示
vimpMonkey('(www|encrypted)\\.google\\.co(m|\\.jp)/search',
  function() {
    if (content.getComputedStyle(content.document.getElementById('hidden_modes'),'').display == 'none') {
      unsafeContent.google.x('showmodes', {apply: function(){unsafeContent.google.srp.toggleModes()}});
    }
  });

Vimperatorのautocmdで-jsオプションを使った時

autocmdで-jsオプション使うと{cmd}はfunction(args){with(args){ }}でラップされる
argsには以下のプロパティがある

url URL
title タイトル
tab イベントの起きたタブが何番目か?(1オリジンなのでtabs.getTab(tab-1)とすべし
doc tabs.getTab(上記tabの値-1).linkedBrowser.contentDocument (※文字列なのでevalするといい)