2013/10/30

初嚐 Greasemonkey: LpTable


有時會想要在任意的網頁上加入一些特殊設定或是需要重新排版成看起來比較爽的頁面,舉例來說:在 facebook 的登入畫面做一個快速切換帳號的按紐;又或是最近在用 Lauchpad 的 bugs 覺得它的排版很鳥,所以自己重新用 jQuery 的 tablesorter 重新排一下。

想要解決這樣的問題,一來是可以寫瀏覽器的外掛來改,二或是用我今天要介紹的方法 userscript 來達成,以 firefox 的使用者需要先安裝 greasemonkey,chrome 的使用者則要安裝 tampermonkey

這次就 Launchpad 為例,原先 Launchpad 的 bug 列表長這樣



經過了 LpTable 的 script 會變這樣



Firefox 的使用者來說,在安裝完 greasemonkey 後,再到 LpTable 的頁面按下 Install 即可使用了


基本上寫這些 script 如果已有網頁基本能力寫起來很容易,因此我就在做 LpTable 用到的一些手法來介紹。


jQuery


要在 userscript 裡載入其他 javascript 檔,只需在檔頭的部分加入 @require filepath 即可,如下:

// @require     http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.2.js
// @require     http://datatables.net/release-datatables/media/js/jquery.dataTables.js


CSS


要加入自訂的 CSS 也有幾種方法可以用,舉例來說第一種用 GM_getResourceText,再用 GM_addStyle 將樣式加入,在使用之前記得要先用 @grant 取得權限。又或是用比較原始的的手法,自己建立一個 style element 插在 head 裡如下:

function initStyleSheets() {
    function addGlobalStyle(css) {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    }

    var css_alert = '.alert {padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; color: #468847; background-color: #dff0d8; border-color: #d6e9c6}';

    addGlobalStyle(css_alert);
    var stylesheets = ['https://dl.dropboxusercontent.com/u/23905041/media/css/demo_table.css',
                       'https://dl.dropboxusercontent.com/u/23905041/media/css/jquery.dataTables.css'
                       ];
    $.each(stylesheets, function(index, value) {
        var link = window.document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = value;
        document.getElementsByTagName("HEAD")[0].appendChild(link);
    });
}


Persistent Storage


要將某些資料存起來,在下次 reload 網頁時再用,可用 GM_getValue and GM_setValue 這組 API。使用前記得要 grant 權限,


TableSorter


最後是關於網頁表格的應用,跟 greasemonkey 完全沒關係。當初是希望能有一個表格,可輕鬆動態插入資料,排序,過濾資料,google 一下很快就找到了 TableSorter 這個 jQuery plugin。這部分的線上文件範例都超多,自己網上看看吧。

1 comment:

Kunlin Lee said...

大大你第二張圖掛了