Is it possible to e.preventDefault in [removed]?

后端 未结 2 1250
刺人心
刺人心 2021-01-08 00:21

I\'m trying to stop the user from going back in my web app. For this I tried catching the window.onpopstate and added e.preventDefault to cancel th

相关标签:
2条回答
  • 2021-01-08 01:12

    According to this documentation, the popstate event is not cancellable:

    Specification: HTML5
    Interface: PopStateEvent
    Bubbles: Yes
    Cancelable: No
    Target: defaultView
    Default Action: None

    0 讨论(0)
  • 2021-01-08 01:21

    First off "not possible" is never an acceptable answer.

    Secondly you can compensate for popstate bugs. In example my rich editor has to constantly compensate for the lazy-bastard key: Backspace. It's not a valid key for a back button (just like spacebar for "page downing") but people impose their personal preferences upon the world instead of adding a browser extension so when people press it sometimes the popstate is triggered instead of the editor removing whatever character is to the left of the keyboard caret.

    The following code (dependencies in my platform's documentation) detects when the popstate bug is triggered, slaps it in the face with a e.preventDefault(); and then fixes the address bar address with history.go(1);. The person using the editor doesn't notice anything happened as the browser was not allowed to manipulate the DOM. This code is minimal (other people may be compensating for this bug in various contexts) and I've only tested this in Gecko/Firefox currently so be sure to test Blink, Presto, Trident and WebKit based browsers as well.

    window.onpopstate = function(e)
    {
     if (id_('editor') && is_node_parent(document.activeElement,id_('editor')))
     {
      e.preventDefault();
      history.go(1);
     }
    }
    
    0 讨论(0)
提交回复
热议问题