最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - It is possible to Restore context menu - Stack Overflow

programmeradmin1浏览0评论

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 have MyContextMenu to be called anymore for the next invocations of the contextmenu. – t.niese Commented Nov 6, 2013 at 22:40
Add a ment  | 

3 Answers 3

Reset to default 5

Reassign 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.

发布评论

评论列表(0)

  1. 暂无评论