on Jun 18th, 2009Greasemonkey 技巧

Greasemonkey 会把对象包裹起来返回 XPCNativeWrapper,写 JS 的时候需要留心。下面这些要点来自 Greasemonkey Hacks

1. 调用函数

1
2
3
4
5
//工作
window.setTimeout(my_func, 1000)

//不工作
window.setTimeout("my_func()", 1000)

2. 事件处理

1
2
3
4
5
6
7
8
9
10
//工作
var elmLink = document.getElementById('somelink');
elmLink.addEventListener("click", my_func, true);

//不工作
var elmLink = document.getElementById('somelink');
elmLink.onclick = my_func;

var elmLink = document.getElementById('somelink');
elmLink.onclick = 'my_func(this)';

3. 命名表单和表单元素

1
2
3
4
<!--假如有表单-->
<form id="gs">
    <input name="q" type="text" value="foo" />
</form>
1
2
3
4
5
6
7
//工作
var form = document.forms.namedItem("gs");
var input = form.elements.namedItem("q");
var q = input.value;

//不工作
var q = document.gs.q.value;

4. 自定义属性

1
2
3
4
5
6
7
//工作
var elmFoo = document.getElementById('foo');
elmFoo.setAttribute('myProperty', 'bar');

//不工作
var elmFoo = document.getElementById('foo');
elmFoo.myProperty = 'bar';

5. 迭代集合

1
2
3
4
5
6
7
8
9
10
11
//工作
for (var i = 0; i &lt; arInputs.length; i++) {
    var elmInput = arInputs[i];
    …
}

//不工作
var arInputs = document.getElementsByTagName("input");
for (var elmInput in arInputs) {
    …
}

6. scrollIntoView

1
2
3
4
5
6
7
8
//工作
var elmFoo = document.getElementById('foo');
var elmUnderlyingFoo = elmFoo.wrappedJSObject || elmFoo;
elmUnderlyingFoo.scrollIntoView();

//不工作
var elmFoo = document.getElementById('foo');
elmFoo.scrollIntoView();

7. location

1
2
3
4
5
//工作
window.location.href = "http://example.com/";

//不工作
window.location = "http://example.com/";

8. 调用远程页面脚本

1
2
3
4
5
6
7
8
9
//工作
var searchForm = getNode("s");
searchForm.elements.namedItem("q").value = this.getRunnableQuery();
top.js._MH_OnSearch(unsafeWindow, 0);

//不工作
var searchForm = getNode("s");
searchForm.elements.namedItem("q").value = this.getRunnableQuery();
top.js._MH_OnSearch(window, 0);

9. watch

1
2
3
4
5
6
7
//工作
unsafeWindow.watch("location", watchLocation);
unsafeWindow.location.watch("href", watchLocation);

//不工作
window.watch("location", watchLocation);
window.location.watch("href", watchLocation);

10. 样式

1
2
3
4
5
6
7
8
//工作
var elmFoo = document.getElementById("foo");
elmFoo.style.margin = 0;
elmFoo.style.padding = 0;

//不工作
var elmFoo = document.getElementById("foo");
elmFoo.setAttribute("style", "margin:0; padding:0;");

Trackback URI | Comments RSS

Leave a Reply