Bookmarklet 的小技巧
七月 11, 2008
簡介
Wikipedia : http://en.wikipedia.org/wiki/Bookmarklet
A bookmarklet is an applet, a small computer application, stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. The term is a portmanteau of the terms bookmark and applet.
Bookmarklet,就是存放在書籤(Firefox, Opera)或我的最愛(IE)的 javascript 小程式。
運用
有些現成實用的 bookmarklet 可以參考「電腦玩物: Bookmarklets放在書籤裡的實用瀏覽器小工具補完列表」的詳細介紹。
安裝
- Firefox
直接將[範例]拖曳到「書籤工具列」即可。 - IE
在[範例]點滑鼠右鍵,選擇「加到我的最愛」,會出現安全性警訊:「您正在新增一個可能並不安全的我的最愛。要繼續嗎?」選是即可。 - Opera
在[範例]點滑鼠右鍵,選擇「將連結加入書籤」
型式
開頭一定是「javascript:」
簡單型
- javascript:alert(document.cookie):顯示當前網站的cookie資訊
函式型
- javascript:void(location.href=’http://tinyurl.com/create.php?url=’+location.href) :取得當前網址的tinyurl。
- javascript:(function(){location.href=’http://tinyurl.com/create.php?url=’+location.href})() :取得當前網址的tinyurl。
技巧
物件別名
以下程式片段可自動判別瀏覽器並取得使用者已選取的文字。
var selected = ''; if ( window.getSelection ) selected=window.getSelection(); else if ( document.getSelection ) selected=document.getSelection(); else if ( document.selection ) selected = document.selection.createRange().text;
別名精簡後
S=''; w=window; d=document; if(w.getSelection)S=w.getSelection(); else if(d.getSelection)S=d.getSelection(); else if(d.selection)S=d.selection.createRange().text;
方法別名
以下程式片段可自動填入帳號密碼登入。
document.getElementById('uid').value='aaa';
document.getElementById('pwd').value='xxx';
document.getElementById('logon').click();
別名精簡後
$=document.getElementById;
$('uid').value='aaa';
$('pwd').value='xxx';
$('logon').click();
其它
- 在URL中傳遞文字最好用 encodeURIComponent 處理過。
- 程式碼中的空格要用 %20 取代。
- 開啟新視窗 window.open
- 計時器 setTimeout
- 小幫手:Bookmarklet Builder。可以幫忙縮排程式碼。
取得網頁資訊
- 網址:location.href
- 標題: document.title.replace(/^s*|s*$/g,"")||"" (去掉頭尾的空白)
綜合運用
模仿 twitio.us 將目前在看的網頁發送到 twitter,改成發送到 buboo 並可帶出使用者已選取的文字內容。[線上展示]
javascript:
(function(){
d=document;
w=window;
F=encodeURIComponent;
S=d.selection.createRange().text;
T=d.title.replace(/^s*|s*$/g,"")||"";
U="http://klcin.tw/ap/po3/post-buboo.php?url="+F(location.href)+"&title="+F(T)+"&excerpt="+F(S);
w.open(U,"postBuboo","width=600,height=500,location,status,scrollbars,resizable,dependent=yes");
setTimeout("postBuboo.focus()");
}
)()