PhantomJSのリモートデバッギング的なアレ
Posted: Updated:
Remote Debugging
Remote debugging permits inspection of the script and web page via another WebKit-based browser (Safari and Chrome). Troubleshooting · ariya/phantomjs Wiki
PhantomJSにおける地獄のconsoleデバッグよりも、場合によってはマシかもしれないリモートデバッグのメモ。
phantomjs --remote-debugger-port=9000 test.js
--remote-debugger-port オプションで、ポート番号を指定するとリモートデバッガにアクセスできる。上記の例であれば、http://localhost:9000 で開ける。
手順
- --remote-debugger-port:9000オプションつきでphantomsを叩く (ポート番号はお好きに)
- http://localhost:9000 を開く
- about:blank のリンクを開く -> PhantomJSのプロセスを対象としたWebインスペクター(A)が開く
- Console から __run()を実行する
- page.open()のコールバックから- debuggerを実行する
- http://localhost:9000 をもう1枚開く
- PhantomJS 内で開いているページのリンクを開く 対象ページのWebインスペクター(B)が開く
- Webインスペクター(A)からステップを進める
- page.evaluateAsyncのコールバックから- debuggerを実行する
- Webインスペクター(B)を開くと、任意のタイミングで止まってる
適当サンプル
Troubleshooting · ariya/phantomjs Wiki のサンプルを愚直に実行するとこうなる。
var page = require('webpage').create();
function debugPage() {
  console.log('Refresh a second debugger-port page and open a second webkit inspector for the target page.');
  console.log('Letting this page continue will then trigger a break in the target page.');
  debugger;
  page.evaluateAsync(function() {
    debugger;
  });
}
page.open('http://google.com', function() {
  debugPage();
});
ちなみにこのオプションは、CasperJSでもちゃんと実行できるので、Casperで統合テストを書くときちょっと便利かもしれない。debugger の差し込み周りを整理すれば取り回しはマシになると思われる。
