Greasemonkey脚本和函数范围 [英] Greasemonkey Script and Function Scope

查看:90
本文介绍了Greasemonkey脚本和函数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的脚本代码:

    // ==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将该函数解析到页面上,如。还有另外一种方法吗?

The only issue I have is when Hello World is clicked the page cannot find the test() function. Please tell me I don't have to solve it by innerHTML'ing the function onto the page like this. Is there another way?

谢谢。

推荐答案

Greasemonkey执行沙箱中的脚本 - 出于安全原因,页面无权访问它。所有对dom和window的接受都是通过包装器。

Greasemonkey executes the script in a sandbox - the page doesn't have access to it for security reasons. All acceses to dom and window are via wrappers.

如果你想访问不安全的对象,你可以使用 wrappedJSObject 物业。

If you want to access the unsecured objects you can use wrappedJSObject property.

对于您的情况,您可以使用 unsafeWindow (或 window.wrappedJSObject ):

For your case you can use unsafeWindow (or window.wrappedJSObject):

unsafeWindow.test = function() { ....

这有一些安全问题,请参阅: http://wiki.greasespot.net/UnsafeWindow

There are some security issues with this, see: http://wiki.greasespot.net/UnsafeWindow

此外,greasemonkey在DOMContentLoaded之后执行脚本(当dom准备就绪时) )事件所以你不需要那个onload废话。

Also, greasemonkey executes the script after the DOMContentLoaded (when the dom is ready) event so you don't need that onload nonsense.

另外,你不能使用属性来设置事件监听器或属性 - 你必须使用dom api为此。例如:

Also, you can't use attributes to set event listeners, or properties for that matter - you must use dom api for that. Eg:

t.firstChild.addEventListener('click', test, false);

或:

t.firstChild.addEventListener('click', function(event){ blabla }, false);

这篇关于Greasemonkey脚本和函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆