Related
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?
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.
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:
Making custom right-click context menus for my web-app, which relies on jQuery
How to add a custom right-click menu to a webpage, which uses pure javascript/html
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.
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.
If you are a jquery fan,use this
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
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!
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.
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.
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.
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:
After Implemented On Same Image:
Tested working in both Chrome and Firefox.
Just do this
write oncontextmenu on body tag
<body oncontextmenu="return false">
<!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>
Simple Way:
<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Do it like below (It works on firefox too):
$(document).on("contextmenu",function(e){
if( e.button == 2 ) {
e.preventDefault();
callYourownFucntionOrCodeHere();
}
return true;
});
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>
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.
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.
<script>
window.oncontextmenu = function () {
console.log("Right Click Disabled");
return false;
}
</script>
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>
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
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());
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:
A working hardware
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/
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
};
});
$(document).ready(function () {
document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
});
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();
});
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.
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.
Javascript:
document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false");
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.
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; }
}
I've written two HTML files:
Login.html
Next Page
Home.html`
<html>
<body>
<a href = >Login.html>>Prev Page</a>
</body>
<script type = "text/javascript" >
history.pushState("anything", "", "#1");
window.onhashchange = function (event) {
window.location.hash = "a";
};
</script>
</html>
`
I'm trying to disable browser's back button. If i execute this code on chrome it doesn't disable the back button but if i run history.state command in console of Home.html page and then i click the back button, then it remains on same page(works as expected). Why so?
FOA, Thanks everyone for your answers.
Finally below code gave me the solution:
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
You can't disable the browser's back button. If you could, that would be a security hazard and the browser vendors would most likely seek to fix it.
It is generally a bad idea overriding the default behavior of web browser. Client side script does not have the sufficient privilege to do this for security reason.
There are few similar questions asked as well,
How can I prevent the backspace key from navigating back?
How to prevent browser's default history back action for backspace button with JavaScript?
You can-not actually disable browser back button. However you can do magic using your logic to prevent user from navigating back which will create an impression like it is disabled. Here is how, check out the following snippet.
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var noBackPlease = function () {
global.location.href += "#";
// making sure we have the fruit available for juice (^__^)
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};
}
})(window);
This is in pure JavaScript so it would work in most of the browsers. It would also disable backspace key but key will work normally inside input fields and textarea.
Recommended Setup:
Place this snippet in a separate script and include it on a page where you want this behavior. In current setup it will execute onload event of DOM which is the ideal entry point for this code.
Working Demo link-> http://output.jsbin.com/yaqaho
The HTML5 History API gives developers the ability to modify a website's URL without a full page refresh. This is particularly useful for loading portions of a page with JavaScript, such that the content is significantly different and warrants a new URL.
You can check this link it may helpful
https://css-tricks.com/using-the-html5-history-api/
I have this script in my aspx page
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = function(e) {
return 'Bye now!';
};
</script>
But this is not invoked when I close the browser. I need to pop an alert asking the user to confirm. I need to do this in the aspx page using javascript. The browser I tried was mozilla firefox. Thanks
The following code should fix your issue:
(function () {
window.unloader = function(e) {
(e || window.event).returnValue = null;
return null;
};
window.addEventListener("beforeunload", window.unloader);
})();
You are not going to be able to specify a message, it is defaulted by the browser.
I have this code that alert when I click a link or refresh or close tab.
But I need alert only on close window (tab). how to do this? I have many external and internal links on my site.
<html>
<head>
<script type="text/javascript">
window.onbeforeunload = function (e) {
var e = e || window.event;
//IE & Firefox
if (e) {
e.returnValue = 'Are you sure?';
}
// For Safari
return 'Are you sure?';
};
</script>
</head>
<body>
<!-- this will ask for confirmation: -->
<!-- I need to alert for external links. -->
external link
<!-- this will ask for confirmation: -->
<!-- I don't need to alert for local links in my web site -->
internal link
</body>
</html>
document.activeElement is handy in this scenario, it will be equal to the link you click on to unload the page. You can then check the link's href attribute whether it contains your host name. An example for codepen.io would be (demo here):
window.onbeforeunload = function (e) {
var e = e || window.event;
var element = document.activeElement;
if(element.tagName === 'A' && element.href.indexOf('codepen.io/') === -1) {
//IE & Firefox
if (e) {
e.returnValue = 'Are you sure?';
}
// For Safari
return 'Are you sure?';
}
};
My initial thought was to do a regex for http:// and https:// to see if the path is relative but it looks like browsers basically convert relative paths to absolute and prepend the http...
If you want to write this code so that it is more universal you can use location.hostname instead of statically typing the hostname to do a comparison on.
Finally, your milage may vary in IE depending on which IEs you want to support the above code might need updated. The trend nowadays is to support IE11+ :)
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?
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.
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:
Making custom right-click context menus for my web-app, which relies on jQuery
How to add a custom right-click menu to a webpage, which uses pure javascript/html
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.
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.
If you are a jquery fan,use this
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
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!
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.
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.
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.
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:
After Implemented On Same Image:
Tested working in both Chrome and Firefox.
Just do this
write oncontextmenu on body tag
<body oncontextmenu="return false">
<!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>
Simple Way:
<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Do it like below (It works on firefox too):
$(document).on("contextmenu",function(e){
if( e.button == 2 ) {
e.preventDefault();
callYourownFucntionOrCodeHere();
}
return true;
});
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>
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.
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.
<script>
window.oncontextmenu = function () {
console.log("Right Click Disabled");
return false;
}
</script>
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>
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
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());
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:
A working hardware
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/
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
};
});
$(document).ready(function () {
document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
});
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();
});
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.
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.
Javascript:
document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false");
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.
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; }
}