Aran Mulholland
Aran Mulholland

Reputation: 23935

Disable Undo and Redo in browsers

I would like to disable undo and redo in all browsers using JavaScript. I want to do this as our app has it's own undo and redo history built in.

I can already handle key presses to disable undo and redo via a keyboard entry but I would like to disable the menu items as well. (Standard menu and right click menu)

Is this possible? Even if it is only possible in some browsers it would be better than none.

Upvotes: 7

Views: 4943

Answers (4)

JDMCreator
JDMCreator

Reputation: 1

Using my library undo.js, you can disable undo and redo actions (not just from shortcuts) using the following code:

undo.observe(document.body, {
    preventDefault:true
});

You can then capture requests from the user for undo and redo actions (using a shortcut or the browser menu) using:

myeditor.addEventListener("undo", function(e){
    // whatever...
});
myeditor.addEventListener("redo", function(e){
    // whatever...
});

Upvotes: 0

Chris R
Chris R

Reputation: 276

I know this is old, but for others that are curious, this worked for me.

$(window).bind('keydown', function(evt) { 
  if((evt.ctrlKey || evt.metaKey) && String.fromCharCode(evt.which).toLowerCase() == 'z') {
    evt.preventDefault();
  }
});

Upvotes: 4

Omer Faruk Zorlu
Omer Faruk Zorlu

Reputation: 380

it is not possible using browser apis. but there is a few ways to detect or handling methods. url hashing is a one way to handling back or forward event. however browsers not support this for user safety. you can search javascript url hashing scripts but do not forget about that scripts compatible with html5 browsers.

Upvotes: 0

Tibos
Tibos

Reputation: 27823

One thing you can do is intercept the popstate event. Unfortunately i don't think it can be canceled, so you have to hack it up a bit by adding a dummy state to undo to.

The following code prevented me from pressing back on Chrome and FF. Feel free to test it on other browsers.

window.setTimeout(function(){
  window.history.pushState({}, '', '#');
  window.addEventListener("popstate", function() {
    window.history.pushState({}, '', '#');
  });
},1000);

Make sure to change your code as appropriate to fit in with your own history. Also consider using the HTML5 History API instead of your own history implementation.

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Upvotes: 1

Related Questions