Vanilla JS: Totally disabling a “save” functionality in webpages

前端 未结 4 1674
Happy的楠姐
Happy的楠姐 2021-01-23 23:54

Assume I\'m a junior Wikipedia user that just want to experiment with changing some wikipedian content with the Wiki text editor in an edit-page, but not saving my changes in an

4条回答
  •  长发绾君心
    2021-01-24 00:12

    There are a number of problems in your question:

    • event.key isn't the same as event.keyCode, Refer to the documentation.
    • e.key == 16 && e.key == 18 && e.key == 83 will never be true.
    • Returning false from an event listener doesn't stop the event from being propagated.

    What you are trying to do can be achieved in the following way:

    document.addEventListener("keypress", evt => {
      // refer to https://stackoverflow.com/a/2878005/8746648
      if(evt.altKey && evt.key == "S") {
        alert("prevent this message");
        evt.preventDefault();
      }
    });
    
    // refer to https://stackoverflow.com/a/35611393/8746648
    document.addEventListener("keypress", evt => {
      if(evt.altKey && evt.key == "S") {
        evt.stopPropagation();
      }
    }, true);

    1. Notice the true in the second event listener.
    2. Notice that evt.key is compared with an upper case "s".
    3. You can't prevent an event listener from running if it's registered in the capturing phase. (read about the capture and blobbing phases here).

提交回复
热议问题