这是我的脚本代码:
// ==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() 函数。请告诉我,我不必通过将函数 innerHTML'ing 到页面上来解决它,例如 this .还有别的办法吗?
谢谢。
最佳答案
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);
关于javascript - Greasemonkey 脚本和函数作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/551028/