0

I'm writing a plugin that needs to operate on arbitrary sites, and needs to prevent the url from changing.

Using e.preventDefault works to prevent normal anchor links from changing the url.

However any active javascript event handlers on site can still update the url. Unless I'm severely mistaken using e.stopImmediatePropagation doesn't solve this issue, since there's no way to guarantee that 'my' event handler containing e.stopImmediatePropagation is the first event handler being run. (Again, because I don't control the site)

Now I can prevent all clicks from happening by the 'hack' of placing a transparent element under the mouse on mousedown and remove it again on mouseup.

However, that prevents any other click-interaction that doesn't result in a url change. If at all possible I'd like to keep these interactions enabled.

Any solutions that help me get out of this conundrum?

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • You could swap out the `a` element for something that doesn't produce a navigation action, like a `span` when you want to disable it. Hide the anchor, show the span, the reverse it when you want to enable it again. – Sam Axe Oct 19 '16 at 08:16
  • Agreed that would solve most of it. However, there may be behavior/ handlers attached to `a` that don't result in a location change (e.g.: javascript dropdowns) which I'd like to keep intact if possible. Replacing `a` with another element removes those handlers as well. – Geert-Jan Oct 19 '16 at 08:19
  • 1
    http://stackoverflow.com/questions/2073086/javascript-how-to-intercept-window-location-change - it doesnt stop form submittals, but you didnt ask about those :) – Sam Axe Oct 19 '16 at 19:53
  • 1
    Since events are executed in the order they are attached, you could try removing all events ([list events](http://stackoverflow.com/a/16544813/74015)) and then attaching *your* handler, and then reattaching the previously attached events (try to preserve their attachment order). – Sam Axe Oct 19 '16 at 20:00

0 Answers0