Bud*_*Joe 7 javascript firefox greasemonkey scope
这是我的脚本代码:
// ==UserScript==
// @name test
// @description test
// @include http://*
// @copyright Bruno Tyndall
// ==/UserScript==
var main = function() {
var b = document.getElementsByTagName('body')[0];
var t = document.createElement('div');
t.innerHTML = '<a href="javascript:void(0);" style="color:white;">Hello World</a>';
t.style.position = 'absolute';
t.style.zIndex = 1000;
t.style.bottom = '5px';
t.style.right = '5px';
t.firstChild.setAttribute('onclick', 'test();');
b.appendChild(t);
}
var test = function() {
alert("Hello World");
}
main();
Run Code Online (Sandbox Code Playgroud)
我唯一的问题是当单击Hello World时页面无法找到test()函数.请告诉我,我没有通过innerHTML'ing功能上类似的页面来解决它这个.还有另外一种方法吗?
谢谢.
ion*_*lmc 14
Greasemonkey在沙箱中执行脚本 - 出于安全原因,页面无权访问它.所有对dom和window的接受都是通过包装.
如果要访问不安全的对象,可以使用wrappedJSObject
属性.
对于您的情况,您可以使用unsafeWindow
(或window.wrappedJSObject
):
unsafeWindow.test = function() { ....
Run Code Online (Sandbox Code Playgroud)
这有一些安全问题,请参阅:http://wiki.greasespot.net/UnsafeWindow
此外,greasemonkey在DOMContentLoaded(当dom准备就绪)事件之后执行脚本,因此您不需要那个onload废话.
此外,您不能使用属性来设置事件侦听器或属性 - 您必须使用dom api.例如:
t.firstChild.addEventListener('click', test, false);
Run Code Online (Sandbox Code Playgroud)
要么:
t.firstChild.addEventListener('click', function(event){ blabla }, false);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13095 次 |
最近记录: |