简体   繁体   中英

How to override an event in Javascript whatever the library previously used to bind it?

I'm trying the greasemonkey extension for firefox in order to override some JavaScript events on the websites I visit.

For instance, I want to display a message when the blur event has been bound to the window element, whatever the page I visit.

I thought it was pretty easy. But it is much harder to make this working on every case, because depending on the library the website uses, the JavaScript events seems to be stored in different places.

Here is a test I have made in a greasemonkey user script :

window.onload = function(event) {    
    // Handle pure JS
    if (window.onblur) {
       console.log('There is a blur event on the window element of this page');
    }

    // Handle jQuery
    if (window.jQuery) {
        var jExpando = window[window.jQuery.expando];

        if (jExpando.events.blur) {
            console.log('There is a blur jQuery event on the window element of this page');
        }
    }
}

This works on every page that uses pure JavaScript or jQuery, but I'm not able to catch blur events listeners of other libraries such as Mootools, Prototype...

Thus, this is pretty bad code, considering I have to handle all the existing JavaScript libraries myself and I have no idea how to do that.

Is there a way to get all event listeners bind on a specific JavaScript object (whatever the library used to attached them) so I can override some of them?

Most libraries use addEventListener, so you'll want to override that with a function of your own. Be sure to keep a reference to the original addEventListener method so the events can still be added.

I have an example Greasemonkey script here: http://userscripts.org/scripts/show/174829

It will listen to all events and tell you which ones were added. Obviously, you can modify this to make 'blur' events not register.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM