展開所有 GitHub comment 的 Bookmarklet

看到 Eric Meyer 弄了一個可以展開 GitHub comment 的 bookmarklet:「Bookmarklet: Load All GitHub Comments」。

分析他的程式碼,稍微手動排一下,可以看出來邏輯蠻簡單的,就是去找出對應的 button,然後模擬按下去的 event:

javascript:function start() {
  let buttons = document.querySelectorAll('button');
  let loaders = [];
  for (let i = 0; i < buttons.length; i += 1) {
    if (buttons[i].textContent.trim() == 'Load more%E2%80%A6') {
      loaders.push(buttons[i]);
      buttons[i].dispatchEvent(new MouseEvent('click', {
        view: window,
        bubbles: false
      }))
    }
  }
  if (loaders.length > 0) {
    setTimeout(start, 5000)
  }
}
setTimeout(start, 500);
void(20240130);

意外可以看到一些應該是作者以前寫習慣的寫法 (畢竟 Eric Meyer 這個名字二十年前就聽過了?),現在 for 拿來當 iteration 應該會用 of 的語法了,另外是 letconst 的差異...

還好這邊還是用 querySelectorAll(),而不是直接看到 getElementsByTagName(),不然就更有考古感了...

拿「Quadratic time internal base conversions #90716」這個測了一下還行,不過我不是那麼常用到,大概不會掛到 bookmark bar 上面...

作者有提到考慮過寫成 userscript,不過看起來是懶 XD

Usability 測試的 bookmarklet

在「Usability: Don't Make Me Think and a Bookmarklet」這篇文章裡作者在讀了「Don’t Make Me Think, Revisited」之後有所啟發,寫了一小段 javascript code,可以將網頁上所有文字都變成同樣長度的亂碼,藉以測試許多 usability 特性。

我把程式碼丟進 yui-compressor 後變成這樣,比較容易貼到 bookmarklet 上使用:

javascript:(function(){var a=" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";$("*:not(iframe)").contents().filter(function(){return this.nodeType==Node.TEXT_NODE&&this.nodeValue.trim()!=""}).each(function(){var c="";for(var b=0;b<this.nodeValue.trim().length;b++){c+=a.charAt(Math.floor(Math.random()*a.length))}this.nodeValue=c})})();

不過這段程式碼假定頁面上有 $ 這個 object (i.e. jQuery),所以我把程式碼改成吃 jQuery 這個 object,這樣確保 jQuery.noConflict() 後的網站還是可以動:

javascript:(function(){var a=" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";jQuery("*:not(iframe)").contents().filter(function(){return this.nodeType==Node.TEXT_NODE&&this.nodeValue.trim()!=""}).each(function(){var c="";for(var b=0;b<this.nodeValue.trim().length;b++){c+=a.charAt(Math.floor(Math.random()*a.length))}this.nodeValue=c})})();

效果如下,還蠻有趣的: