430

Can I disable right click on my web page without using JavaScript? I ask this because most browsers allow user to disable JavaScript.

If not, how do I use JavaScript to disable right click?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Vinay Pandey
  • 8,589
  • 9
  • 36
  • 54
  • 172
    Disabling right click isn't security, it's just annoying your users. Any browser that doesn't let you disable this is worthless, but sites that do it in the first place are terrible. – Dan Olson Apr 10 '09 at 08:30
  • 27
    If you do not want your content taken, you should not post it on the web. :) Modern day browsers can even override JavaScript's ability to disable right click. Tools like Firebug/ Web Dev Toolbar make protection useless. – epascarello Apr 10 '09 at 12:34
  • 11
    here is a small chrome/greesemonkey user script to re-enable right click: http://dl.dropbox.com/u/464119/Programming/javascript/enable-rightclick.user.js – ripper234 Sep 14 '11 at 10:42
  • 36
    Really @DanOlson... what are you supposed to do if you want to code your own right-click menu? Such as found in cPanel. – Codesmith Sep 15 '13 at 20:50
  • 4
    @AUTO: Not do that either, because cPanel is a shining example of a bad UI? People don’t expect to right-click on things on the web. – Ry- Nov 18 '13 at 15:27
  • 5
    @minitech What about a lot of Google's Web Apps? Such as gmail, they override the right click on a lot of stuff there. – Tom Heard Nov 19 '13 at 20:30
  • 3
    @TomHeard: Yep, I find it counterintuitive, personally. It makes some sense if you’re trying to make a Docs-esque clone of desktop software where that kind of thing is expected, though. – Ry- Nov 19 '13 at 23:42
  • 36
    @epascarello there are certain cases that disabling right click is essential, like on kiosk terminals, bceause user actually doesn't need it there and leaving it there may actually annoy the users – Aram Mar 19 '14 at 07:31
  • 4
    Right click disabling is an absolute necessity on touchscreen interfaces. – user734063 Jul 30 '14 at 22:05
  • Personally, I want to disable right click so that the user can use the page a lot more efficiently. If any user wants to see the source, they can easily do so by accessing one of the browser menu's :) – MiJyn Sep 26 '14 at 17:31
  • 2
    This may be more of an edge case, but I'm here trying to remember how to do it for an html5 kiosk. The user should never be able to do anything that could take them out of the kiosk unexpectedly. – Dave_750 Nov 05 '14 at 15:24
  • Not to beat a dead horse here, but Google's own Web Developer starter kit pages (documentation and everything) have right clicks disabled, and they're not 'editor-esque'. They don't replace the right click menu with anything either, its just... disabled. See: https://developers.google.com/web/fundamentals/layouts/rwd-fundamentals/set-the-viewport – Abhishek Nov 30 '14 at 10:24
  • 2
    I am trying to find out how to do this so that I can STOP my right-click from being disabled, on a page I am unfortunately stuck using. – Abacus Feb 11 '15 at 16:06
  • Usually I would be totally against disabling right click but for an application we're building it's necessary in *some* places. I still thing people who disable this fully across a site need a reality check though – Adam Hughes May 09 '17 at 15:45
  • 1
    Chrome extension to [enable right-click](https://chrome.google.com/webstore/detail/enable-right-click/hhojmcideegachlhfgfdhailpfhgknjm?hl=en) – evilReiko Jun 13 '17 at 09:48
  • 7
    web development is NEVER cut and dry as "Don't ever do ____ because it's bad", and pretending that it is is bad development. I'm developing a physical kiosk that would totally ruin UX if a user started messing around with the right click menu.... – little tiny man May 25 '18 at 02:17
  • 2
    Thus a reminder that discouragement alone is never a sufficient answer to how can I do [so and so]. – Samie Bencherif Jan 05 '19 at 20:51
  • simple way: – Mr. Newbie May 06 '21 at 05:05
  • Sometimes it's useful when you make your own context menu and disable the firefox one instead. Interactive apps like Discord have their own menu and they got the default one disabled too so I don't think it's "terrible". It's very subjective. – Thielicious Feb 04 '23 at 08:24
  • 3 dots -> More tools -> Developer tools. Done. Ez right click bypass. All you're preventing me from doing is getting Chrome to translate your page into my language (which is in the right click menu). – aggregate1166877 Mar 03 '23 at 23:16
  • Considering right click "wrong" is short sighted, as well as assuming the purpose of such a feature is primarily to prevent others from viewing source. Any modern website is developed to operate as an application to at least some degree, not as a document. "Save", "Print", "Reload" etc all assume that the page is a document. They are not relevant to most pages, at least not when it comes to volume of use on todays internet. All browsers should give the ability to at least add, remove and customize items, even if some (such as print or view source) are considered required. – JSON Jul 03 '23 at 06:14

30 Answers30

733

You can do that with JavaScript by adding an event listener for the "contextmenu" event and calling the preventDefault() method:

document.addEventListener('contextmenu', event => event.preventDefault());

That being said: DON'T DO IT.

Why? Because it achieves nothing other than annoying users. Also many browsers have a security option to disallow disabling of the right click (context) menu anyway.

Not sure why you'd want to. If it's out of some misplaced belief that you can protect your source code or images that way, think again: you can't.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
cletus
  • 616,129
  • 168
  • 910
  • 942
  • 3
    its not really "javascript or html" , its only really "and", as the "html only" way will require javascript, which if is not available/disabled, will not run. – Kent Fredric Apr 10 '09 at 08:28
  • 133
    Using `oncontextmenu="return false"` on something else than the body may make sense, for example on a canvas. – AdrienBrault Jan 13 '13 at 13:52
  • 1
    @cletus disable right click is necessary somewhere Suppose you are taking an online quiz and don't want that your questions can be copied and searched on google.So in short it depends on condition – bugwheels94 Jun 15 '13 at 18:31
  • 79
    We are deploying onto kiosk machines and chose this way to disable users from refreshing the page. – Todd Horst Jul 31 '13 at 20:08
  • 27
    @ToddHorst in that case I'd use a special "Kiosk" version of the browser without any UI, which usually is also available without any context menus :) – mihi Nov 18 '13 at 18:38
  • @cletus `mousedown` does not work any more. Your answer should be updated to using `contextmenu`. – hitautodestruct Dec 04 '13 at 13:01
  • 3
    It's useful if you're dealing with interactive graphics and an accidental right click messes with the interaction... – Alex Jul 06 '14 at 19:51
  • 25
    Touch-enabled systems sometimes map certain touch events, such as a long tap, to the right-click (and thereby opening the context menu). However, this behaviour can be undesirable and the only meaningful way of preventing it seems to be disabling the context menu altogether. – O. R. Mapper Aug 15 '14 at 13:12
  • @O.R.Mapper : Yes! I'm facing similar issues with disabling right-click on a touch overlay screen, and the touch events map to right-click despite being turned off via other methods (e.g. AutoHotKey, touch settings in Control Panel). – stellarchariot Sep 11 '14 at 22:56
  • 93
    Old Thread but in case someone reads it, not all the web developers make their websites for themselves sometimes the customer comes to you and insist in disabling the right click, when you try to convince him he will just look for another developer who will do it without hesitation – DJ22T Sep 23 '14 at 20:57
  • the only use case for this is when you have replaced the menus with your own – 1-14x0r Mar 26 '15 at 18:25
  • 1
    The JS method in the answer does not work (in chrome at least). This is simple and reliable. `document.getElementById('meetingBody').oncontextmenu = function() {return false;};` Where meetingBody was my body tag. – Paul Haggo Mar 30 '15 at 20:10
  • 3
    We embed web browser content areas into our desktop applications and we don't want users to be able to right-click to, for example, view the source or properties of the page. This is another good example of when you might want to disable right-click on a webpage. – qJake May 28 '15 at 14:41
  • It also should be noted that while this isn't security, a lot of Japanese companies have it in contracts that images should be protected from right click saving... It makes no sense but you have to do this sometimes. – Will Reese Feb 08 '16 at 04:26
  • 5
    Downvote. I need this for right-click panning on my map. I think it's pretty legitimate. Your answer doesn't work on the canvas element I'm using. – Tomáš Zato Apr 08 '16 at 12:48
  • 2
    We need this so our non-technical customers don't do stupid things, like touch and hold, then open up the developer tools and call us asking what the new feature is and how they're supposed to use it. (Most of out users are technical idiots.) So sometimes there is a legitimate use for this. – senschen Nov 02 '16 at 14:19
  • 10
    I need to disable the right click context menu for certain parts of my browser game. Think twice before you tell people "don't do this" – Chris Rollins Mar 10 '17 at 08:39
  • Browsers are designed and developed according to standards. Stop trying to hack core browser functionality. Right-clicking is expected, predictable behaviour. Disabling it rarely makes sense. Stop trying to bind your actions to a right-click? That's oftentimes a poor design solution. – Michel Joanisse Nov 09 '17 at 21:09
  • 10
    DO NOT is only relative to the use case. Perhaps you should not use it for a simple websites however web technologies are used in lots of places. We use HTML interfaces in kiosk browsers with touchscreens in a factory; the touchscreens see the dirty fingers sometimes as right click - preventing right click solved this problem. – rofavadeka Nov 12 '17 at 13:26
  • 4
    Hey, I just want to disable right-click on slither because sometimes I accidentally right-click when playing, and then I die. – ErikE Dec 09 '17 at 21:00
  • News sites that gatekeep their content behind sign-up modals do this too. Example: https://digital.elmercurio.com It still feels like a terrible experience, but oh well – Eamon Bohan Oct 24 '19 at 20:27
  • 4
    One use case I haen;t seen here is, videogames and other 3D simultions. You may want to repurpose the right click for additional commands for navigation and such – Makogan Dec 12 '19 at 17:05
  • `viewsource://` ;) – Captain Jack Sparrow Nov 30 '20 at 04:03
  • It is sometimes the case that the right click be mapped to custom options that the user is "used to" from other basic applications. Like right clicking and having a copy, cut and paste option which are developed through eventListeners in JS. – analytical_prat Apr 22 '21 at 11:28
  • You could go to about:inspect in chromium based browser so it won't help – Justin Liu May 05 '21 at 00:51
  • 5
    `That being said: DON'T DO IT.` This is a personal opinion, and personal opinions, while welcome, should not be stated in a way that represents that they are fact. For those interested, lots of big sites do this. Gmail is an example off the top of my head. I am pretty sure half the world uses gmail and likely few of you ever noticed you cannot right click in certain regions. There are plenty of good reasons to disable right clicking. Websites with active content, html based games, apis, sensitive fields and much more. –  Aug 22 '21 at 04:32
  • 1
    I used to feel there was no legitimate use case for disabling right click on a website, but recently I was helping a young child who was new to computers use an educational website. They were not used to using a mouse and kept accidentally right-clicking and clicking items in the context menu (take screenshot, block element, etc.). I came here to so I could get the JS to paste into the console and disable right click myself. – bmaupin Oct 18 '21 at 21:31
  • 2
    Everyone saying "don't do it", havs not considered all purposes. Some of us have built kiosk mode apps, where everything the user needs is already on the interface. The abilities of the kiosk user is the purpose of being limited only to the app, or in this case page. Disabling right-click is just an extra added on limitation that you would want for your kiosk mode users, as they should not be trying to right-click and look at the code in the first place. - I can' understand the "don't do it" response if the app is built for the public, for kiosk mode purpose there's definitely a need. – MarlonC Jul 24 '22 at 05:47
  • 1
    @bmaupin I ended up here for the same reason. I'm making a programming environment to use in my classes with young children. They will right click by accident and end up in all sorts of weird places. – Wowfunhappy Aug 16 '22 at 22:09
  • 2
    Just a random Comment here, "don't do it" isn't really an advice, disabling the context menu is a feature and it should be used, what if i'm building a web design platform, i want to allow the user to use his mouse in a beneficial way because the original context menu is meaningless in my app concept. – jadinerky Oct 01 '22 at 19:16
  • 2
    "Because it achieves nothing other than annoying users" - so you think if I'm making a remote desktop application, not having another context menu pop up on top of the relevant one, making it actually possible the use the one you wanted to, is "annoying"? – Heath Mitchell Mar 22 '23 at 11:59
  • 1
    I wanna use it to roll my own context menu for a full window canvas app – circl Aug 19 '23 at 18:27
  • the question is "[How] can I disable right click on my web page without using JavaScript?" OP is not asking for advice on best practices or usability design. – Arajay Aug 20 '23 at 21:02
135

DON'T

Just, don't.

No matter what you do, you can't prevent users from having full access to every bit of data on your website. Any Javascript you code can be rendered moot by simply turning off Javascript on the browser (or using a plugin like NoScript). Additionally, there's no way to disable the ability of any user to simply "view source" or "view page info" (or use wget) for your site.

It's not worth the effort. It won't actually work. It will make your site actively hostile to users. They will notice this and stop visiting. There is no benefit to doing this, only wasted effort and lost traffic.

Don't.

Update: It seems this little topic has proven quite controversial over time. Even so, I stand by this answer to this question. Sometimes the correct answer is advice instead of a literal response.

People who stumble on this question in hopes of finding out how to create custom context menus should look elsewhere, such as these questions:

Community
  • 1
  • 1
Wedge
  • 19,513
  • 7
  • 48
  • 71
  • 22
    @GAgnew: There are valid uses to replace the context menu. There are no valid users to disable rightclicks unconditionally and without handling them in a useful way- – ThiefMaster Jun 06 '12 at 07:06
  • 11
    Had to -1 for the same reason as @GAgnew, but I do realize that "protecting" content is _probably_ what the user was after. Another reason _not_ to _freak out_ about disabling right click, is that the business goal may be to make it _harder_ to copy content for _most_ people. Geeks != most users. – peteorpeter Jun 06 '12 at 16:10
  • 111
    If the user wants to make a HTML5 videogame, disabling the right click could be quite useful. Usually, this is not desirable, but just saying "DON'T" without the proper context is not that helpful. – Robson França Oct 26 '12 at 04:54
  • On the other hand, I can't imagine how to disable right click without Javascript... – Robson França Oct 26 '12 at 04:56
  • 1
    @ThiefMaster I recently had to make a script that lets you select items on a page with an action that involved the right click. The context menu was interfering with that. It's a perfectly valid use case. – Sebastián Grignoli Nov 06 '12 at 17:48
  • 2
    @SebastiánGrignoli: Then the use-case is not called "disable right click" though – ThiefMaster Nov 06 '12 at 17:50
  • 3
    @peteorpeter The OP was probably after protecting his contents, but the question is "How do I disable right click on my web page?" and some people arrive here from search engines looking for a legitimate answer to that question. – Sebastián Grignoli Nov 06 '12 at 17:50
  • @ThiefMaster Right, in my case it was "disable context menu" – Sebastián Grignoli Nov 06 '12 at 18:40
  • 19
    -1. Moral arguments aren't the point of SO. If he wants to disable right click, he probably has a reason- not that you bothered to find out. Perhaps you could rephrase your comment with a suggestion on how NOT to annoy your users while doing this to make this post not a waste of time. Google docs has right click disabled- I suppose you'd choose to call up the tech lead and tell him he's annoying every user on Gdocs? – dudewad Feb 01 '13 at 17:31
  • 74
    -1 from me, too. This answer isn't helpful. There are plenty of good reasons to disable right click. For example, I created a web application that hospitals use at the front desk, and the users are not technically savvy. Even though the application is running in their web browser, they don't understand why all the menu options come up when they right click. We got tons of help questions asking us what the options are for, from people who thought they were part of the application. Disabling them made sense in that case, and does in many other web applications. – Nicholas Apr 24 '13 at 22:00
  • 10
    I hardly get stackoverlow, sometimes. If a user asks how to plant a nail in his head the correct answer is "with a hammer". Then (and, imvho only then) add: "I think this is not a good idea because a, b, c." – Pitto May 16 '13 at 08:31
  • 8
    Moreover, this is actually a very pretentious answer. Nowadays there are quite the reasons for disabling right-click context menu, just open your google drive page to see a righteous example. – WDRust May 16 '13 at 10:20
  • 6
    What about a video game UI in HTML? – Vortico Mar 05 '14 at 02:32
  • Here in fact is a perfectly valid reason to disable right-click: 1) I want to share an image with just one person, and I do not want that person (or anyone else) to retain a copy of that image. 2) I happen to know that this one person is not a sophisticated user. 3) Therefore I put the image on the web, send the user the URL, with a warning that the URL will expire in five minutes, and five minutes later, I take the image off the web. 4) I am aware that this is not foolproof, but it seems pretty safe and I'm willing to take the risk. – WillO Jun 20 '14 at 02:04
  • @WillO: If your user finds the *File* -> *Save as* command of their browser, that won't help much. – O. R. Mapper Aug 15 '14 at 13:15
  • @ThiefMaster: Touch-enabled systems sometimes map certain touch events, such as a long tap, to the right-click (and thereby opening the context menu). However, this behaviour can be undesirable and the only meaningful way of preventing it seems to be disabling the context menu altogether. – O. R. Mapper Aug 15 '14 at 13:15
  • 1
    Downvote from me. Just yesterday my kid accidentally clicked RMB then "go back" resulting in loosing points. One shoe size does not fit all. – greenoldman Jan 11 '15 at 11:40
  • 4
    I'm making a level editor, who has an action bound to right click. This is a perfect valid and not "evil" case, just on one div. Maybe you should add that you're not obliged to bind this HTML event to body but only on one div ? – romualdr May 26 '15 at 01:09
  • 3
    This is not a useful answer. I have a website that is meant for a certain small pool of customers. They have to enter credentials just to see these pages with product images. These users are not technically sophisticated. For them, using the right-click "save as" would be the limit of their abilities. Even if a few can figure it out, that's okay, but the majority will not. So this is a perfectly valid use-case where it is meant to make things a little more secure, even if it is not foolproof, and it is on a private site. – Pete Jun 16 '15 at 18:49
  • 11
    This is a terrible answer, in part because it does not answer the question and in part because it automatically assumes that the asker is attempting to hide their javascript. I came looking for a way to hide it because the right click menu was getting in the way of page function - and instead I get "don't hide your code!" –  Jun 21 '15 at 16:56
  • 2
    This does not answer the question - giving advice is good but please also consider giving an real answer. Now a days web technologies are used in many places any if you should or should not do this really depends on the use case. Personally we disabled this on many touch devices running kiosk applications were there was absolutely no use for this. Accidentally double tapping and opening developer tools lead to a lot of confusion by the factory workers. Disableling right click solved this issue. – rofavadeka Nov 12 '17 at 14:10
  • 1
    Someone better go tell Google Drive they are using terrible web design! – slaw Mar 28 '18 at 02:06
  • 1
    I am developing a webapp for an experiment where users swipe through images as quickly as possible while making decisions. We want to disable anything that might interrupt or distract from the task. The long press menu (the mobile browsers' answer to the right click menu) is one of these things. – personalnadir Jun 22 '18 at 10:05
  • 3
    In developing web based video games, right clicking is frequently expected to perform an in-game function, not bring up a browser context menu. – leiavoia Aug 06 '18 at 18:11
  • 2
    There are a lot of situation you want to block the context menu in the UI. You are always able to open dev console, if you have full access to your system. Sometimes you just dont want to see the context menu. Simple as that – Johan Hoeksma Jun 30 '19 at 18:09
  • 3
    How is this an answer? OP wanted a solution to: "Disabling Right Click on a Web page" - they didn't ask for your opinion, or whether they should do it or not. Sure, you're entitled to leaving your thoughts on the topic, but atleast provide some feedback that could help them solve their issue. There are many reasons why you would want to disable the right-click context menu on a web page. For starters, in web-based games. Sure the Developer Tools can be easily opened else where, but people may want to use the right-click button for different functionalities in their game. – Nanoo Jul 02 '20 at 12:38
  • It's surprising how this answer assumes that generally users know how to a) disable javascript in a browser b) view the source code. Most of the cases where disabling the right click is required, it is done to just make it difficult for the users to get there. A lot of users won't even choose to do the effort. – Talha Imam Sep 07 '21 at 11:32
  • `No matter what you do, you can't prevent users from having full access to every bit of data on your website.` How utterly presumptuous. Why do you *assume* that this is only to try to protect images from being downloaded? I'm trying to create a button that can have different functions depending on whether the user left or right clicks instead of creating multiple buttons. Others want to make **games**. Not every use is DRM. – Synetech Apr 14 '23 at 00:22
87

The original question was about how to stop right-click given that the user can disable JavaScript: which sounds nefarious and evil (hence the negative responses) - but all duplicates redirect here, even though many of the duplicates are asking for less evil purposes.

Like using the right-click button in HTML5 games, for example. This can be done with the inline code above, or a bit nicer is something like this:

document.addEventListener("contextmenu", function (e){
    e.preventDefault();
}, false);

But if you are making a game, then remember that the right-click button fires the contextmenu event - but it also fires the regular mousedown and mouseup events too. So you need to check the event's which property to see if it was the left (which === 1), middle (which === 2), or right (which === 3) mouse button that is firing the event.

Here's an example in jQuery - note that the pressing the right mouse button will fire three events: the mousedown event, the contextmenu event, and the mouseup event.

// With jQuery
$(document).on({
    "contextmenu": function (e) {
        console.log("ctx menu button:", e.which); 

        // Stop the context menu
        e.preventDefault();
    },
    "mousedown": function(e) { 
        console.log("normal mouse down:", e.which); 
    },
    "mouseup": function(e) { 
        console.log("normal mouse up:", e.which); 
    }
});

So if you're using the left and right mouse buttons in a game, you'll have to do some conditional logic in the mouse handlers.

unrealapex
  • 578
  • 9
  • 23
Mr Speaker
  • 3,047
  • 24
  • 17
  • If I've enabled [`dom.event.contextmenu.enabled`](http://kb.mozillazine.org/About:config_entries#DOM.) in Firefox, will the `mousedown` and `mouseup` events still fire even if `contextmenu` doesn't? – robertc Nov 01 '12 at 16:05
74

If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.

Omar Wagih
  • 8,504
  • 7
  • 59
  • 75
  • 2
    Yes, but there are times when I want to briefly share an image with someone who I am aware is lacking in basic browser knowledge. Disabling right click is not 100% foolproof, but if I'm posting the image for just a few minutes to let that person have a look, it's pretty safe. – WillO Jun 20 '14 at 02:11
  • 2
    Touch-enabled systems sometimes map certain touch events, such as a long tap, to the right-click (and thereby opening the context menu). However, this behaviour can be undesirable and the only meaningful way of preventing it seems to be disabling the context menu altogether. – O. R. Mapper Aug 15 '14 at 13:18
  • 1
    @WillO: I have a similar use-case I need to cater, but FYI, users will always resort to **screenshots**. – Hassan Baig Feb 17 '18 at 15:25
28

If you are a jquery fan,use this

    $(function() {
        $(this).bind("contextmenu", function(e) {
            e.preventDefault();
        });
    }); 
  • 11
    This is using jQuery for no reason. This does exactly the same as the single JavaScript statement found in Mr. Speaker's answer, which was posted 1½ years before this. By the way, that answer also includes a jQuery solution, which again you don't need. Does anyone who had upvoted this answer even know what this does? Why does this wait for the document ready event to stop preventing the context menu from appearing? Why does this use `this` inside the ready event? Why do you use `bind` instead of `on`? – Rudey Mar 28 '18 at 16:25
25

If your goal is to disallow users to simply save your images, you can also check if the clicked target is an image, only disable right click in that case. So right click can be used for other purposes. Taken from the code above:

document.addEventListener("contextmenu", function(e){
    if (e.target.nodeName === "IMG") {
        e.preventDefault();
    }
}, false);

This is just to take away the easiest way of saving your images, but it can still be done.

Andrew
  • 510
  • 5
  • 6
  • This is in my opinion the best way to go - as a web user I find the right click functionality useful from time to time but as an easy, simple (and yes, easily beatable) solution this works without being annoying. – Ben Nov 14 '16 at 15:15
25

First, you cannot achieve this without using a client side capability. This is where the javascript runs.

Secondly, if you are trying to control what an end user can consume from your site, then you need to rethink how you display that information. An image has a public url that can be fetched via HTTP without the need for a browser.

Authentication can control who has access to what resources.

Embedded watermarking in images can prove that the image was from a specific person/company.

At the end of the day, resource management is really user/guest managment.

The first rule of the Internet, if you dont want it taken, dont make it public!

The second rule of the Internet, if you dont want it taken, dont put it on the Internet!

Wayne
  • 3,415
  • 1
  • 22
  • 21
23

If your aim is to prevent people being able to download your images, as most people have said, disabling right click is pretty much ineffective.

Assuming you are trying to protect images the alternative methods are -

Using a flash player, users can't download them as such, but they could easily do a screen capture.

If you want to be more akward, make the image the background of a div, containing a transparent image, à la -

<div style="background-image: url(YourImage.jpg);">
   <img src="transparent.gif"/>
</div>

will be enough to deter the casual theft of your images (see below for a sample), but as with all these techniques, is trivial to defeat with a basic understanding of html.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
benophobia
  • 771
  • 6
  • 8
18

You cannot accomplish what you're asking without using Javascript. Any other technology you may choose to use can only help to compose the web page on the server side to be sent to the browser.

There simply is no good solution, and there is no solution period without Javascript.

Anthony
  • 7,086
  • 1
  • 21
  • 22
  • 2
    And even then its annoying for the users, not to mention easy to bypass. – Manos Dilaverakis Apr 10 '09 at 08:16
  • 3
    I've only ever seen pages which have a modal popup saying 'right click is disabled', which then shows the right-click menu when you dismiss it. They also display the message when you scroll using trackpad, which is very annoying. – Pete Kirkham Apr 10 '09 at 08:18
  • 2
    Yea, it's especially annoying since usually it's to prevent people from "stealing" images which are already on their harddrive, but all it does is prevent me from using Context Search: https://addons.mozilla.org/en-US/firefox/addon/240 . Those bastards... – Calvin Apr 10 '09 at 08:38
  • 4
    I love how almost every answer to this is "Sure, use javascript!" – Charles Wood Nov 18 '13 at 18:34
17

If you just want to disable right click for saving images on the web page, go with this CSS solution:

your-img-tag {
  pointer-events: none;
}

Before Implemented On Same Image: Before

After Implemented On Same Image: After

Tested working in both Chrome and Firefox.

Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
13
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(function(){
$('img').bind('contextmenu', function(e){
return false;
}); 
});//]]>  
</script>
</head>
<body>
    <img src="http://www.winergyinc.com/wp-content/uploads/2010/12/ajax.jpg"/>
</body>

aravind3
  • 272
  • 3
  • 11
  • 1
    [`dom.event.contextmenu.enabled`](http://kb.mozillazine.org/About:config_entries#DOM.) – robertc Nov 01 '12 at 16:04
  • 3
    @aravind3 I used your example and it works a treat! My images are still clickable and function the way they are supposed to, but are unable to be downloaded. The reason I wanted to disable right-clicking is that visitors that only want an image and then leave straight away are effecting my bounce rate. At least this way, my bounce rate won't be quite as bad, as it might take them 1 or 2 mins to figure it out :) Cheers aravind3!!!! – coolydude Feb 28 '13 at 21:11
12

Simple Way:

<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Mr. Newbie
  • 382
  • 5
  • 17
7

Do it like below (It works on firefox too):

$(document).on("contextmenu",function(e){

     if( e.button == 2 ) {
         e.preventDefault();
          callYourownFucntionOrCodeHere();
     }
return true;
});
nntona
  • 409
  • 4
  • 9
7

There are three most popular following ways of disabling a right mouse click on your webpage.

#1 Using HTML Body Tag

<body oncontextmenu="return false;">

#2 Using CSS

body {
    -webkit-user-select: none;  /* Chrome all / Safari all */
    -moz-user-select: none;     /* Firefox all */
    -ms-user-select: none;      /* IE 10+ */
    -o-user-select: none;
    user-select: none;
}

#3 Using JavaScript

document.addEventListener('contextmenu', e => e.preventDefault());
Oleksa O.
  • 827
  • 8
  • 16
6

Put this code into your <head> tag of your page.

<script type="text/javascript"> 
function disableselect(e){  
return false  
}  

function reEnable(){  
return true  
}  

//if IE4+  
document.onselectstart=new Function ("return false")  
document.oncontextmenu=new Function ("return false")  
//if NS6  
if (window.sidebar){  
document.onmousedown=disableselect  
document.onclick=reEnable  
}
</script>

This will disable right click on your whole web page, but only when JavaScript is enabled.

Antony
  • 14,900
  • 10
  • 46
  • 74
tejas
  • 77
  • 1
  • 1
6

I had used this code to disable right click in any web page, Its working fine. You can use this code

jQuery(document).ready(function(){
  jQuery(function() {
        jQuery(this).bind("contextmenu", function(event) {
            event.preventDefault();
            alert('Right click disable in this site!!')
        });
    });
});
<html>
  <head>
    <title>Right click disable in web page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
    You write your own code
  </body>
</html>
arvinda kumar
  • 679
  • 8
  • 6
6

Of course, as per all other comments here, this simply doesn't work.

I did once construct a simple java applet for a client which forced any capture of of an image to be done via screen capture and you might like to consider a similar technique. It worked, within the limitations, but I still think it was a waste of time.

Cruachan
  • 15,733
  • 5
  • 59
  • 112
4
    <script>
        window.oncontextmenu = function () {
            console.log("Right Click Disabled");
            return false;
        }
    </script>
Anbu
  • 490
  • 6
  • 20
2

I know I am late, but I want to create some assumptions and explainations for the answer I am going to provide.

Can I disable right-click

Can I disable right click on my web page without using Javascript?

Yes, by using JavaScript you can disable any event that happens and you can do that mostly only by javaScript. How, all you need is:

  1. A working hardware

  2. A website or somewhere from which you can learn about the keycodes. Because you're gonna need them.

Now lets say you wanna block the enter key press here is the code:

function prevententer () {
 if(event.keyCode == 13) {
  return false;
 }
}

For the right click use this:

event.button == 2

in the place of event.keyCode. And you'll block it.

I want to ask this because most browsers allow users to disable it by Javascript.

You're right, browsers allow you to use JavaScript and javascript does the whole job for you. You donot need to setup anything, just need the script attribute in the head.

Why you should not disable it?

The main and the fast answer to that would be, users won't like it. Everyone needs freedom, no-one I mean no-one wants to be blocked or disabled, a few minutes ago I was at a site, which had blocked me from right clicking and I felt why? Do you need to secure your source code? Then here ctrl+shift+J I have opened the Console and now I can go to HTML-code tab. Go ahead and stop me. This won't add any of the security layer to your app.

There are alot of userful menus in the Right Click, like Copy, Paste, Search Google for 'text' (In Chrome) and many more. So user would like to get ease of access instead of remembering alot of keyboard shortcuts. Anyone can still copy the context, save the image or do whatever he wants.

Browsers use Mouse Navigation: Some browsers such as Opera uses mouse navigation, so if you disable it, user would definitely hate your User Interface and the scripts.

So that was the basic, I was going to write some more about saving the source code hehehe but, let it be the answer to your question.

Reference to the keycodes:

Key and mouse button code:

http://www.w3schools.com/jsref/event_button.asp

https://developer.mozilla.org/en-US/docs/Web/API/event.button (would be appreciated by the users too).

Why not to disable right click:

http://www.sitepoint.com/dont-disable-right-click/

Kim Minseo
  • 113
  • 1
  • 1
  • 7
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
2

Try This

<script language=JavaScript>
//Disable right mouse click Script

var message="Function Disabled!";

function clickIE4(){
if (event.button==2){
alert(message);
return false;
 }
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false")

</script>
Dipesh
  • 387
  • 6
  • 16
2

Disabling right click on your web page is simple. There are just a few lines of JavaScript code that will do this job. Below is the JavaScript code:

$("html").on("contextmenu",function(e){
   return false;
});

In the above code, I have selected the tag. After you add just that three lines of code, it will disable right click on your web page.

Source: Disable right click, copy, cut on web page using jQuery

  • This is jQuery, not javascript. The user is looking for ways to disable right click behavior with javascript disabled. – Arajay Aug 20 '23 at 20:59
1
 $(document).ready(function () {
            document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
        });
soheil bijavar
  • 1,213
  • 2
  • 10
  • 18
1

Important Note: It depends on browser and OS to allow such prevention or not!

Should you do it? No. Because it will not prevent the user, but it will just annoys him/her.

Can you use it? Yes. Examples: In some web-apps where you want to have customized pop-up menu, in-game where users might be annoyed when mistakenly they right-click, and other cases.

Chrome (v65) in Ubuntu 16.04 = You CAN disable right-click.

Chrome (v65) in Mac OS 10.11 = You CAN NOT disable right-click.

Chrome (v65) in Windows 7 = You CAN NOT disable right-click.

Firefox (v41) in Mac OS 10.11 = You CAN disable right-click.

Firefox (v43) in Windows 7 = You CAN disable right-click.

// Vanilla JS way
document.addEventListener('contextmenu', function(e){
    e.preventDefault();
});

// jQuery way
$(document).bind('contextmenu', function(e) {
    e.preventDefault();
});
jartaud
  • 375
  • 5
  • 19
evilReiko
  • 19,501
  • 24
  • 86
  • 102
1

Try this code for disabling inspect element option

    jQuery(document).ready(function() {
    function disableSelection(e) {
        if (typeof e.onselectstart != "undefined") e.onselectstart = function() {
            return false
        };
        else if (typeof e.style.MozUserSelect != "undefined") e.style.MozUserSelect = "none";
        else e.onmousedown = function() {
            return false
        };
        e.style.cursor = "default"
    }
    window.onload = function() {
        disableSelection(document.body)
    };

    window.addEventListener("keydown", function(e) {
        if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 67 || e.which == 70 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {
            e.preventDefault()
        }
    });
    document.keypress = function(e) {
        if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 70 || e.which == 67 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {}
        return false
    };

    document.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 123 || e.keyCode == 18) {
            return false
        }
    };

    document.oncontextmenu = function(e) {
        var t = e || window.event;
        var n = t.target || t.srcElement;
        if (n.nodeName != "A") return false
    };
    document.ondragstart = function() {
        return false
    };
});
Agan116
  • 37
  • 9
  • 2
    Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Jan 31 '20 at 14:37
  • 1
    This can be *extremely* easy to override in Chrome: Click on the 3 dots next to your profile picture > More Tools > Developer Tools – sportzpikachu Mar 12 '20 at 09:37
0

Javascript:

document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false"); 
Sos.
  • 914
  • 10
  • 14
0

A few things to consider:

Browser Plugins like "enable right click" in the chrome store exist for a reason, and you wont be able to get around them. There is LITERALLY NOTHING you can do to stop people from downloading your content as they literally have to download it to even see it in their browser anyway; People try but its always out there.

In general, if content shouldn't be public, don't put it online.

Also, not being able to right click is an accessibility issue and amounts to unlawful discrimination against the blind or disabled or elderly in many cases. Check you local laws, but in the USA its actively against the law in the form of the Federal ADA as the blind or the elderly who may have vision issues are a legally protected class.

So instead of doing this and wasting a lot of time and effort, don't even bother trying to do this. It could just get your company sued or have them fail a compliance audit.

honestduane
  • 579
  • 6
  • 13
0

Yes, you can disable it using HTML and Javascript.
Just add oncontextmenu="return false;" on your body or element.
It is very simple and just uses valid HTML and Javascript, no jQuery.

Tiago Rangel
  • 1,159
  • 15
  • 29
-1

Use this function to disable right click.You can disable left click and tap also by checking 1 and 0 corresponding

document.onmousedown = rightclickD;
            function rightclickD(e) 
            { 
                e = e||event;
                console.log(e);
                if (e.button == 2) {
                //alert('Right click disabled!!!'); 
                 return false; }
            }
CodeBreaker
  • 395
  • 2
  • 9
-1

I'd like to add a note (for chrome 97) not sure if this is a bug related to chrome or my environment.
Right clicking on a specific element of my application opens a page in a new tab, using mousedown and oncontextmenu="return false" I was still having the contextual menu appearing, even on the new opened page (Only the menus of installed chrome extensions appear on that contextual menu, I think this "bug" should get fixed in future version of the browsers).

But in the meantime I fixed it using this simple hack

function onMouseDown () {
  setTimeout(() => window.open('the link', '_blank'), 100)
}

I am just deferring the tab opening. I think this bug occurs because the right click is caught by the new opened page, not from the original page of my application that tries to open the tab.

Hope it saves you from headaches.

vdegenne
  • 12,272
  • 14
  • 80
  • 106
-1

I don't see any point for that, only developers usually go to the console tab by clicking right-click. Eventually, we can also go there with the help of Ctrl + Shift + I. There you go.