2008年4月18日

jQuery and Geasemonkey Notes



Greasemonky: 一個 Firefox/IE 下的 Addon,可以另外寫 Javascript Script 在於特定網頁的 Client 端執行。
jQuery: 一套 javascript library,用在協助做 HTML DOM element 處理。


◎ 最基本在 <head> 內加上下面這行即可做 jQuery  的功能
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>


若要有 XPath 處理的擴充功能的話,則還要加
 
<script type="text/javascript"
src="http://dev.jquery.com/view/trunk/plugins/xpath/jquery.xpath.js">
</script>


◎ jQuery 的操作可以參考這裡:jQuery 的基本教學


 ◎ Dive Into Greasemonkey: 詳細的 Greasemonkey 說明書。


◎ 很多情形若要在網頁載入完畢後才能進行,要用以下的方式:
 
$(document).ready(function(){
// Your code here
);


若是在 Geasemonkey 下則不需要,因為 Geasemonkey 會在整個網頁 load 完才要動作。


而要 jQuery 在 Geasemonkey 內執行則要加段 Code,可參考這裡,這是針對 Firefox 版的,若是要 Greasemonkey for IE 也能 Work,後述有改過的版本。


◎ 基本的 XPath 操作有點不一樣,原本下面的絕對路徑形式
$("/html/body/table[3]/tbody/tr/td/table/tbody/tr/td[2]")


要改成下述 :eq(n-1) 的方式呈現
$("/html/body/table:eq(2)/tbody/tr/td/table/tbody/tr/td:eq(1)")


◎ 若 .html() 的功能,若在 Firefox 正常,而在 IE 下不能 Work 的情形,可以參考這裡,簡單講就是被指定為 child element 時,在 IE 下會有問題,改指定 parent(),比如下面這行不能 Work 的話:
$("tbody/tr/td/table/tbody/tr/td/table/tbody//td/table").eq(1).html(newhtml);


改為下述的情形,應該就會 Work:
$("tbody/tr/td/table/tbody/tr/td/table/tbody//td/table").eq(1).parent().html(newhtml);


◎ 根據這裡,可以在 Greasemonkey 內使用 jQuery,但這個並不能在於 Greasemonkey for IE 內使用,所以,要改成下述的情形,這樣的 javascript 才可在 IE, Firefox 兩邊使用。


最主要似乎是 IE 沒辦法處理 unsafeWindow?? 而且用此方法在 IE 會有第一次讀取 jQuery 不完整就往下執行的情形,我只有在大約五秒之後就直接去執行後續的 script,這個方式只能在 IE7 下做, IE6 仍會有問題。
 
// Add jQuery
var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://code.jquery.com/jquery-latest.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);

// Add jQuery XPath Plugin
var GM_JQ2 = document.createElement('script');
GM_JQ2.src = 'http://dev.jquery.com/view/trunk/plugins/xpath/jquery.xpath.js';
GM_JQ2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ2);

// Check if jQuery's loaded
Browser = navigator.appName;
Net = Browser.indexOf("Netscape");
var count=0;

function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}

window.GM_wait = function() {
if(Net >= 0) {
if (typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
else { $ = unsafeWindow.jQuery; letsJQuery(); }
} else {
while (count<30 && typeof window.jQuery=='undefined')
{
pausecomp(200);
count += 1;
}
window.setTimeout(letsJQuery,100);
}
}
GM_wait();

// All your GM code must be inside this function
function letsJQuery() {
// alert($); // check if the dollar (jquery) function works
// Your code here
}




Orignal From: jQuery and Geasemonkey Notes