2011年8月29日 星期一

跨瀏覽器判斷使用者離開網站(關閉視窗)



網路上很多文章教的都是只能用在IE上,
為了跨瀏覽器, 後來設計了這個方法

想法是把所有會觸發換頁的動作都控制下來
把以下的動作定義為正常的瀏覽, 並應該是停留在原網站內
1. 滑鼠點擊網頁內的元件 (在我的case中沒有任何的外部連結, 有的話也是新開分頁)
2. 按下Enter, F5
3. 非以上的情況都視為是離開網站
4. 以上可視自己網站的需求增加, 另外有任何系統自動化換頁功能時, 需要在換頁前呼叫userEvent


實作 userEvent

var isUserEvent = false;
function userEvent(){
    isUserEvent = true;
    //在觸發userEvent後, 1秒後就將flag清除, 時間設太短有時候網站反應慢一點會誤判
    setTimeout("isUserEvent =false;",1000);
}


1. 滑鼠點擊事件

//用onmousedown的話會遇到使用者按太久沒放開結果isUserEvent又被設為false
document.onmouseup = userEvent;       
 


2. 按下Enter, F5
實作 keyDown

document.onkeydown = keyDown;
function keyDown(e) {
    if (!e) var e = window.event;
    var key = window.event ? e.keyCode : e.which;

    //Enter: 13,  F5: 116
    if(key == 13 || key == 116)
        userEvent();
}


3. 實作 logout

window.onunload = logoutUser;
function logoutUser() {
    // 判斷是離開網站的操作, 並且使用者已經登入, 就幫他做登出的動作
    // 怕誤判的話可以詢問使用者是否要登出
    if (!isUserEvent && isLogin && confirm('logout?')) {
        try {
            var xmlhttp = null;
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //later IE
            } catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //earlier IE
                } catch (e) {
                    xmlhttp = null;
                }
            }

            if (xmlhttp==null)
            {
                xmlhttp=new XMLHttpRequest() //IE7, Firefox, Safari
            }
            //用ajax呼叫登出使用者的api
            xmlhttp.open("POST","/LoginManager.do?opt=logout", false);
            xmlhttp.send();
            return true;
        } catch(e) {

        }
    }
}


2011年2月22日 星期二

grep + sed + xages批次修改檔案內容

egrep -lRZ "\.jpg|\.png|\.gif" . \ 
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g' 
  • egrep: find matching lines using extended regular expressions
  • -l: only list matching filenames
  • -R: search recursively through all given directories
  • -Z: use \0 as record separator
  • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"
  • .: start the search in the current directory
  • xargs: execute a command with the stdin as argument
  • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.
  • -l: use one line per command as parameter
  • sed: the stream editor
  • -i: replace the input file with the output without making a backup
  • -e: use the following argument as expression
  • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"
reference : http://stackoverflow.com/questions/1169927/using-sed-and-grep-to-search-and-replace