How do I disable right click on my web page?
Asked Answered
S

31

445

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?

Suzisuzie answered 10/4, 2009 at 8:12 Comment(21)
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.Satirist
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.Unimproved
here is a small chrome/greesemonkey user script to re-enable right click: dl.dropbox.com/u/464119/Programming/javascript/…Obnubilate
Really @DanOlson... what are you supposed to do if you want to code your own right-click menu? Such as found in cPanel.Horrid
@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.Accomplice
@minitech What about a lot of Google's Web Apps? Such as gmail, they override the right click on a lot of stuff there.Anergy
@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.Accomplice
@Unimproved 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 usersLamed
Right click disabling is an absolute necessity on touchscreen interfaces.Crossman
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 :)Faggot
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.Honeyman
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: developers.google.com/web/fundamentals/layouts/rwd-fundamentals/…Spectra
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.Grefe
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 thoughOrang
Chrome extension to enable right-clickUnfleshly
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....Kentigera
Thus a reminder that discouragement alone is never a sufficient answer to how can I do [so and so].Tussock
simple way: <body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">Oxymoron
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.Photoactive
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).Sailcloth
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.Ninetta
S
747

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.

Sonorous answered 10/4, 2009 at 8:22 Comment(33)
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.Wakeen
Using oncontextmenu="return false" on something else than the body may make sense, for example on a canvas.Couscous
@Sonorous 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 conditionMarkley
We are deploying onto kiosk machines and chose this way to disable users from refreshing the page.Dissuasive
@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 :)Carnallite
@Sonorous mousedown does not work any more. Your answer should be updated to using contextmenu.Thorwald
It's useful if you're dealing with interactive graphics and an accidental right click messes with the interaction...Illegalize
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.Chloropicrin
@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).Jabiru
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 hesitationCristen
the only use case for this is when you have replaced the menus with your ownLocally
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.Cervine
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.Weaponless
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.Frodin
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.Surgeonfish
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.Notch
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"Swot
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.Batting
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.Valleau
Hey, I just want to disable right-click on slither because sometimes I accidentally right-click when playing, and then I die.Newson
News sites that gatekeep their content behind sign-up modals do this too. Example: digital.elmercurio.com It still feels like a terrible experience, but oh wellBettor
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 suchRingsmuth
viewsource:// ;)Tizzy
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.Factory
You could go to about:inspect in chromium based browser so it won't helpDefense
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.Spangler
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.Guardhouse
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.Dorthydortmund
@Guardhouse 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.Calpe
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.Prelusive
"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"?Allantoid
I wanna use it to roll my own context menu for a full window canvas appSamathasamau
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.Ambrosane
P
131

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:

Pleinair answered 10/4, 2009 at 8:28 Comment(28)
@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-Rudyrudyard
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.Absinthe
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.Sumerlin
On the other hand, I can't imagine how to disable right click without Javascript...Sumerlin
@Rudyrudyard 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.Dogeared
@SebastiánGrignoli: Then the use-case is not called "disable right click" thoughRudyrudyard
@Absinthe 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.Dogeared
@Rudyrudyard Right, in my case it was "disable context menu"Dogeared
-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?Armrest
-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.Plasmasol
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."Kynan
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.Lungwort
What about a video game UI in HTML?Idaidae
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.Afresh
@WillO: If your user finds the File -> Save as command of their browser, that won't help much.Chloropicrin
@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.Chloropicrin
Downvote from me. Just yesterday my kid accidentally clicked RMB then "go back" resulting in loosing points. One shoe size does not fit all.Adriaadriaens
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 ?Outwash
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.Formally
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!"Sump
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.Valleau
Someone better go tell Google Drive they are using terrible web design!Acrostic
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.Dregs
In developing web based video games, right clicking is frequently expected to perform an in-game function, not bring up a browser context menu.Tonkin
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 thatMonocular
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.Instructive
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.Goldsmith
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. 🙄Camise
F
88

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.

Freehand answered 10/8, 2012 at 13:37 Comment(1)
If I've enabled dom.event.contextmenu.enabled in Firefox, will the mousedown and mouseup events still fire even if contextmenu doesn't?Vinaya
R
77

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.

Rocher answered 7/6, 2013 at 15:17 Comment(3)
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.Afresh
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.Chloropicrin
@WillO: I have a similar use-case I need to cater, but FYI, users will always resort to screenshots.Oleaster
S
27

If you are a jquery fan,use this

    $(function() {
        $(this).bind("contextmenu", function(e) {
            e.preventDefault();
        });
    }); 
Stomodaeum answered 27/1, 2014 at 12:4 Comment(1)
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?Aparejo
G
26

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!

Gregg answered 10/4, 2009 at 8:24 Comment(0)
M
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.

Midi answered 1/2, 2014 at 11:30 Comment(1)
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.Pancreatin
E
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.

Ecdysis answered 10/4, 2009 at 8:47 Comment(1)
You could even load the image as base64, to further obfuscate the code.Prewitt
K
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.

Karikaria answered 10/4, 2009 at 8:13 Comment(4)
And even then its annoying for the users, not to mention easy to bypass.Regulator
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.Devindevina
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: addons.mozilla.org/en-US/firefox/addon/240 . Those bastards...Calcicole
I love how almost every answer to this is "Sure, use javascript!"Luby
P
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.

Pileum answered 22/10, 2020 at 12:56 Comment(1)
Firefox users can literally press alt to go into the menubar and go to view, then change "Page Style" to "No Style" allowing them to easily bypass this.Fujio
C
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>

Coldhearted answered 21/9, 2012 at 12:27 Comment(2)
dom.event.contextmenu.enabledVinaya
@Coldhearted 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!!!!Geotectonic
O
13

Simple Way:

<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Oxymoron answered 6/5, 2021 at 5:4 Comment(1)
This should be the accepted answer, thanksAlcaide
N
9

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());
Nugent answered 19/5, 2022 at 9:54 Comment(0)
N
7

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

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

     if( e.button == 2 ) {
         e.preventDefault();
          callYourownFucntionOrCodeHere();
     }
return true;
});
Natural answered 6/8, 2015 at 4:19 Comment(0)
E
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.

Eberto answered 10/4, 2009 at 8:52 Comment(0)
L
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.

Lines answered 19/2, 2013 at 14:5 Comment(1)
This does not work on firefox it disable input selection for forms typing :(Blandina
C
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>
Carlocarload answered 30/8, 2018 at 6:57 Comment(0)
T
4
    <script>
        window.oncontextmenu = function () {
            console.log("Right Click Disabled");
            return false;
        }
    </script>
Tempest answered 29/12, 2015 at 6:33 Comment(0)
M
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>
Metaphysic answered 19/10, 2016 at 10:43 Comment(1)
This seems like the most needlessly complex answer possibleAmbrosane
F
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

Fowkes answered 17/10, 2017 at 17:0 Comment(1)
This is jQuery, not javascript. The user is looking for ways to disable right click behavior with javascript disabled.Ambrosane
B
1

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/

Biodegradable answered 10/10, 2013 at 1:3 Comment(0)
R
1
 $(document).ready(function () {
            document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
        });
Renin answered 11/12, 2013 at 13:3 Comment(0)
U
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();
});
Unfleshly answered 13/4, 2018 at 5:46 Comment(0)
R
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
    };
});
Rosenblatt answered 31/1, 2020 at 14:16 Comment(2)
Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve 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.Hamlen
This can be extremely easy to override in Chrome: Click on the 3 dots next to your profile picture > More Tools > Developer ToolsDeicer
M
0

Javascript:

document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false"); 
Menken answered 10/5, 2017 at 12:19 Comment(0)
G
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.

Gaziantep answered 20/2, 2021 at 10:25 Comment(0)
B
-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; }
            }
Butchery answered 18/7, 2019 at 6:31 Comment(1)
Using Javascript to do what HTML already does is bad engineering and wastefulDeutsch
D
-1

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.

Deutsch answered 2/1, 2020 at 18:22 Comment(0)
J
-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.

Jaejaeger answered 6/1, 2022 at 23:15 Comment(0)
C
-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.

Cyclo answered 2/8, 2023 at 8:23 Comment(0)
V
-1

On fresh NextJS Typescript project (or similarly JS), head to layout.tsx, add this to body tag:

<body ... onContextMenu={(e) => e.preventDefault()}>
...
</body>
Volkan answered 14/10, 2023 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.