下面是我的脚本代码:
// ==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();我遇到的唯一问题是,当单击Hello World时,页面无法找到test()函数。请告诉我,我不需要像this那样把这个函数放在页面上来解决这个问题。还有别的办法吗?
谢谢。
发布于 2009-02-15 17:17:11
Greasemonkey在沙箱中执行脚本-出于安全原因,页面无法访问它。对dom和window的所有访问都是通过包装器实现的。
如果你想访问不安全的对象,你可以使用wrappedJSObject属性。
对于您的情况,您可以使用unsafeWindow (或window.wrappedJSObject):
unsafeWindow.test = function() { ....这有一些安全问题,请参阅:http://wiki.greasespot.net/UnsafeWindow
此外,greasemonkey在DOMContentLoaded (当dom准备好时)事件之后执行脚本,所以您不需要那些onload废话。
此外,您不能使用属性来设置事件侦听器或属性-您必须使用dom api。例如:
t.firstChild.addEventListener('click', test, false);或者:
t.firstChild.addEventListener('click', function(event){ blabla }, false);发布于 2009-02-15 15:33:18
iirc,greasemonkey在它自己的作用域内运行,所以test不会在全局命名空间中。
与其污染全局,为什么不通过DOM操作来创建锚元素呢?这将返回一个引用,您可以绑定一个匿名函数(或greasemonkey作用域测试)。
发布于 2009-02-15 15:24:25
尝试将函数测试添加到窗口对象
window.test = function ...编辑
此外,从“load”事件处理程序运行代码也是一个好主意,而不是仅仅在脚本结束时调用它。例如:
window.addEventListener("load", function(e) {
// Your main() here
}, false);https://stackoverflow.com/questions/551028
复制相似问题