简体   繁体   中英

Event.PreventDefault() doesn't always work

I just wanted to make a quick userscript to prevent websites from opening links in new tabs, so I can choose when to do so. Oh boy.

I wanted to use plain javascript; I think it's enough for such an easy task. I was doing all my tests in Quora because that's where I decided I wanted to code that little snippet.

Well, nothing worked. I started simple and went increasing the craziness of my code in light of the failure: the link kept opening no matter how many preventDefault()'s, return false's, prevent[*]Propagation(), eventListeners... Even modifying the dom to strip the a element from its target="_blank".

In the end, I bit my tongue and tried jQuery with this little snippet:

$("a").click(function(event){
        event.preventDefault();
        alert("Was preventDefault() called: " + event.isDefaultPrevented());
    });

But that didn't do any good either. So I gave up. I then realized that the code seemed to work on other websites. Except on Quora.com. A regular Quora link looks like this:

<a href="http://thewebsite.to/go"
    rel="noopener nofollow"
    target="_blank"
    onclick="return Q.openUrl(this);"
    class="external_link"
    data-qt-tooltip="thewebsite.to"
    data-tooltip="attached">
    Link text
</a>

There's plenty of crap there, for sure, but I've been stripping down attributes one by one until the bare bones: <a href="http://thewebsite.to/go"></a> and still doesn't work. Best of all is that even though the link opens, event.isDefaultPrevented() returns true!

Why does that happen and how can I fix it?

You are sure that links getting selected? Maybe this help:

$(document).on('click', 'a', function(e) {
    e.preventDefault();
});

The problem is the onclick definition in the a tag. It creates a new on click event listener before your code does anything.

To prevent it you will have to play around with the event order, see this previous question: How to order events bound with jQuery

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