简体   繁体   中英

DOMSubtreeModified Event (and/or replacement) on solely <a> tags?

I've noticied the DOMSubtreeModified event is being deprecated (which is sad news), but I was wondering if there's a way to detect a change in every single tag on a page (I know - this can be really costly, but it has its purpose).

Basically, I want to know whenever an <a> tag (node) is created/modified so I can quickly scan its .href and see if it matches a pattern I'm looking for (if it is, I want to redirect it to run my JS (irrelevant to this) instead of navigating to said link). I need this to be generic (I don't know IDs/divs/anything except that they're <a href> s, and they have a specific URL pattern I'm looking for.

I know the support for this even is patchy but right now it'd only be used as a Chrome extension (Firefox to come soon after, so I'd have to tinker with it), so it should be okay for now.

Let me know if there are extra questions. Thanks!

You can catch the link action when it happens instead. What is the pattern you are looking for? It's just a matter of "selecting" the right <a> s. jQuery has attribute selectors for just about any occasion, "starts with", "ends with", "contains", "equals", etc...

$('a[href="http://notHere.com"]').on('click',function(event){
    alert("omg don't go there!");
    //window.location="http://www.goHere.com";
    event.preventDefault();
});

jsFiddle

As per comment:

If your page will be changed dynamically you will need to delegate the event binding to something which will definitely always exist, and contain you target.

$('body').on('click','a[href="http://notHere.com"]',function(event){
    alert("omg don't go there!");
    //window.location="http://www.goHere.com";
    event.preventDefault();
});

This puts the click handler on the <body> and from there it watches for clicks on the appropriate anchors. If you can get closer, go for it, eg: $('#mainContent')

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