I'm blocking context menu, then I want to restore it to previous state.
myElement = document.querySelector('*');
myElement.addEventListener('contextmenu', MyContextMenu);
it is possible to restore default context menu after the above code have been executed ? if the answer is yes then how or how to make it correctly?
what i want is to block context menu and then restore it after a while.
I'm blocking context menu, then I want to restore it to previous state.
myElement = document.querySelector('*');
myElement.addEventListener('contextmenu', MyContextMenu);
it is possible to restore default context menu after the above code have been executed ? if the answer is yes then how or how to make it correctly?
what i want is to block context menu and then restore it after a while.
Share Improve this question asked Nov 6, 2013 at 22:33 user971637user971637 1-
Not sure if i understand your question correctly, but you could call
myElement.removeEventListener('contextmenu', MyContextMenu);
at the time where you don't want to haveMyContextMenu
to be called anymore for the next invocations of the contextmenu. – t.niese Commented Nov 6, 2013 at 22:40
3 Answers
Reset to default 5Reassign all context menus to default:
document.querySelector('div').oncontextmenu = _=>false;
var d = document.createElement('div').oncontextmenu;
[...document.querySelectorAll("*")].forEach(e => e.oncontextmenu = d);
<div>sample</div>
Update
Here is a modern version with the "prevent" concept:
document.querySelector('div').oncontextmenu = e => {
e.preventDefault()
return false
}
const fn = document.createElement('div').oncontextmenu
document.querySelectorAll('*').forEach(el => el.oncontextmenu = fn)
<div>sample</div>
Note: This will not work if the event is assigned as an event listener:
document.querySelector('div')
.addEventListener('contextmenu', e => {
e.preventDefault() // <-- problem
return false
})
const fn = document.createElement('div').oncontextmenu
document.querySelectorAll('*').forEach(el => el.oncontextmenu = fn)
<div>sample</div>
var oldHandlerToKeep = element.oncontextmenu
Here's an alternate solution (based on this post by Chema):
document.body.oncontextmenu = null;
document.addEventListener("contextmenu",
function (event) {
event.returnValue = true;
if (typeof(event.stopPropagation) === 'function')
{
event.stopPropagation();
}
if (typeof(event.cancelBubble) === 'function')
{
event.cancelBubble();
}
}, true);
This helps to restore the context menu if preventDefault()
was previously called. Hopefully it might help some passersby.