Mark Highton Ridley
Mark Highton Ridley

Reputation: 136

In a bookmarklet, how can I prevent the context menu when shift-rightclick happens?

I want a bookmarklet to be able to identify the image source when a user holds the shift key and right-clicks an image but I've had trouble working with the obvious event listeners.

I've had no success using an event listener for the contextmenu event and checking for shiftkey being pressed.

I have had some success adding an event listener for mousedown and checking for shiftkey being pressed but the context menu pops up and I can't find out how to prevent this. I only want it prevented when shift is pressed with the mousedown.

Actually I want this for the contextmenu event but will accept using the mousedown event.

This is the code (before pasting into MrColes bookmarklet generator):

handler = function(event) {
    console.log("The doc was mousedowned!");
    if (event.shiftKey) {
        console.log("shift was pressed!");
        console.log("event.srcElement.src: " + event.srcElement.src);
        if (event.srcElement.src === undefined) {
            alert("failed to find image at click position");
        } else {
            myImageSrc = event.srcElement.src;
        }
    }
};
document.addEventListener("mousedown", handler);

Upvotes: 0

Views: 44

Answers (1)

IT goldman
IT goldman

Reputation: 19440

Use contextmenu for the context menu prevention, and use keydown to set a variable that shift has been pressed. Therefore, we must also use keyup to clear the variable.

var obj_down = {}


addEventListener("keydown", function(ev) {
  obj_down[ev.key] = true;
})

addEventListener("keyup", function(ev) {
  delete obj_down[ev.key];
})

addEventListener("contextmenu", function(ev) {
  if (obj_down['Shift']) {
    ev.preventDefault()
  }
})

// attempt for FireFox, but didn't help
addEventListener("mousedown", function(ev) {
  if (obj_down['Shift'] && ev.which == 3) {
    ev.preventDefault()
  }
})
Context menu is disabled when Shift is down.

Upvotes: 0

Related Questions