How do I disable right click on my web page? - javascript

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; }
}

Related

How to use javascript to detect right click when touching image [duplicate]

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; }
}

Getting a href source within the iframe [duplicate]

I got a warning by my ad system provider about click fraud. No further info, all they are recommending is "hide the ads for users who click on ads too quickly'". I wrote a piece of JS script that hides all DIVs with ads for N seconds (using cookie) when clicked on, but this solution does not work as the "inner" content (with ads) is generated by an JS script that calls and renders the content from external server (as you would expect from an ad system). So, when one takes the cross-domain security into account it is kinda Catch 22. How can I detect a click inside a DIV (locally defined) of which content is rendered by an external JS and in iframe?
Example:
<div class="ad-class"> <!-- locally defined div -->
<div id="my-id"> </div> <!-- identifies my ad in the provider's system -->
<script>
var foo = blah // declares the ad dimensions and stuff
// and renders the contextual ad in #my-id DIV
</script>
</div>
Were it all local, solution would be easy as the internal div would inherit the parent class ("ad-class"). In case of cross-domain, this is not valid. Any tips, dudes?
You cannot detect click events in cross-domain iframe.
That put, you might have one bad option:
One of the nearest things you can do is detect that the focus moved from your window to the iframe:
window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
if(document.activeElement == document.querySelector('iframe'))
{
alert('Focus Left Current Window and Moved to Iframe / Possible click!');
}
});
http://jsfiddle.net/wk1yv6q3/
However it's not reliable, loose focus does not mean a click, it could be user moving across the website using TAB.
Another problem is that, you only detect the first time focus is moved to the iframe, you do not know what user does in there, he can click a million times and you will never know.
Luizgrs inspired me this solution :
var clickIframe = window.setInterval(checkFocus, 100);
var i = 0;
function checkFocus() {
if(document.activeElement == document.getElementById("ifr")) {
console.log("clicked "+(i++));
window.focus();
}
}
<!DOCTYPE html>
<h2>Onclick event on iframe</h2>
<iframe src="https://www.brokenbrowser.com/" id="ifr"></iframe>
The function detect if the iframe has the focus, if yes, the user clicked into the iframe. We then give back the focus to our main windows, which allow us to find if the user click another time.
This trick has been usefull to me for a POC on a 2 step iframe click-jacking. Getting to know when the user clicked for the first time on the iframe allowed me to reorganize my different layers to keep the illusion perfect.
The approach #Luizgrs pointed out is very accurate, however I managed to indeed detect the click event using a variation of the method:
var iframeMouseOver = false;
$("YOUR_CONTAINER_ID")
.off("mouseover.iframe").on("mouseover.iframe", function() {
iframeMouseOver = true;
})
.off("mouseout.iframe").on("mouseout.iframe", function() {
iframeMouseOver = false;
});
$(window).off("blur.iframe").on("blur.iframe", function() {
if(iframeMouseOver){
$j("#os_top").click();
}
});
The above code works like a charm on desktop if you want to add mobile support you just need to use touch events touchstartand touchendevents to simulate the mouseover on mobile.
Source
Well, a while ago I found this plugin for WordPress. Obviously it does what I need -- just wondering how this guy made it to work, it does count clicks on Adsense iframe. I must have a closer look though I am not a PHP programmer. I program mainly in Python and need some solution of this kind for Django. If anyone can read the code easily, I would appreciate any help.
The plugin is searching first for any iframe wrapped by a previous specified class name.
The iframe id´s will be collected in a array and for everyone of these id´s an mouseover event will be created which fires the script which hides the class 'cfmonitor'. As a result the iframe containing ad is not visible anymore.
// IFRAME ACTION
function iframeAction () {
jq.each(jq.cfmonitor.iframes, function(index,element) {
frameID = jq(element).attr('id') || false;
if (frameID) initiateIframe(frameID);
//alert (frameID);
});
}
// INIT IFRAME
function initiateIframe(elementID) {
var element = document.getElementById(elementID);
// MOUSE IN && OUT
if (element) {
element.onmouseover = processMouseOver;
element.onmouseout = processMouseOut;
//console.log("mouse on out");
}
// CLICKS
if (typeof window.attachEvent !== 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener !== 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
// IFRAME CLICKS
function processIFrameClick() {
// ADD A CLICK
if(isOverIFrame) {
//addClick();
// Some logic here to hide the class 'cfmonitor'
//console.log("Go");
top.focus();
}
}
Check this it might help. You can not detect the click event when its cross browser.
window.focus();
window.addEventListener('blur', function(e){
if(document.activeElement == document.getElementById('Your iframe id'))
{
console.log('iframe click!');
}
});

Is there a cross browser way to prevent cut, copy and paste on a website in plain Javascript?

I found an answer, but it was for JQuery. Here is the link:
http://jquerybyexample.blogspot.com/2010/12/disable-cut-copy-and-paste-function-for.html
: I want something in plain Javascript which work on chrome, latest firefox, safari, and IE 8 and 9.
Update
Due to all the negative comments saying that this is a bad idea for an internet site I can only say "I agree". Please note that this is for an "intranet" application where cut, copy, and paste need to be overidden as the default browser behaviour for cut copy and paste needs to be customized to handle embedded tags in a rich text area
of course it is not appropriate to do stuff like this, but that was not #Zubairs question, so i think voting down is not correct here, as he made his point clear.
now to the question: if jQuery can do it, native javascript can do it of course too.
you must prevent the cut, copy and paste events:
document.body.oncopy = function() { return false; }
document.body.oncut = function() { return false; }
document.body.onpaste = function() { return false; }
this prevents the right-click-context-menu, this is not needed if you use the 3 other event-handlers but just to let you know ;-)
document.body.oncontextmenu = function() { return false; }
IMPORTANT: the body must be loaded (of course), document.body because IE needs it (document.oncopy will only work in chrome/firefox/safari)
a good way
var D=document.getElementById('b4');
if(D.addEventListener){
D.addEventListener('paste',function(e){false;e.preventDefault();},false);}
else{
D.attachEvent('onpaste',function(){return false;});}
warning : code must be under html target/s ,
just before the close body tag for example
Edit: adding this to a body tag seems to work on all of my test browsers including the Opera, Chrome, Seamonkey (so I assume Firefox) and IE9
<body oncopy='return false' oncut='return false' onpaste='return false'>
you can put them in other tags if you want to allow some functions in some places and not in others
You can catch a [Ctrl]+[C] keypress:
addEventListener("keydown", function(e){
evt = (e) ? e : window.event; // Some cross-browser compatibility.
if(evt.ctrlKey && evt.which == 67){ // [x] == 88; [c] == 67; [v] == 86;
console.log("Ctrl+C pressed!");
evt.preventDefault(); // Cancel the copy-ing function for the client.
// Manual Copy / Paste / Cut code here.
}
});​
Working snippet
oncopy="return false" oncut="return false" onpaste="return false"
This code will be prevent cut, copy and paste of a website.
Working Snippet

Not returning focus to browser after alert pop-up

I am trying to do a little pacman game to train my JavaScript skills. To move pacman around, I use the onkeyup event function associated with a move function.
Still I am having a problem. Every time pacman dies (or game ends) I always use an alert box to alert the user of what happened. Still, after I press the OK button to make pacman move again I must click on the browser window to make it responsive to keyboard events.
Somehow I believe this is a windows focus problem, still, tried to use some focus around (after the alert box mainly) and doesn't seem to do the trick.
Can someone give me general pointers of what could be the solution for this?
PS: In the game construction I am using images created on the fly, having only 2 text tags on the page with id's.
EDIT: code associated in the onkeyup:
function muda_sentido(event)
{
//baixo
if(event.keyCode == 40)
{
pacman_status = status[2];
imagem_pacman.src = "Imagens/pacmanb.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmanb.gif";
}
//direita
else if(event.keyCode == 39)
{
pacman_status = status[0];
imagem_pacman.src = "Imagens/pacmand.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmand.gif";
}
//cima
else if(event.keyCode == 38)
{
pacman_status = status[3];
imagem_pacman.src = "Imagens/pacmanc.gif";
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmanc.gif";
}
//esquerda
else if(event.keyCode == 37)
{
pacman_status = status[1];
imagem_pacman.src="Imagens/pacmane.gif"
imagens[pacman_pos[0]][pacman_pos[1]].src = "Imagens/pacmane.gif";
}
}
html body contents is a double h2 tag (cannot add it to code format cause it appears messed up on the previewer) with an ID each.
And around the program I have something like:
alert("Pacman died!")
And the problem is after this.
2 EDIT: Managed to grab the piece of code that lies the alert box (just changed it now to look for it in only one place):
function pacman_morreu()
{
alert("O pacman morreu!");
if(pacman_vidas==0)
{
alert("Game Over!");
reinicia_tabuleiro();
}
else
{
pacman_vidas--;
vidas.innerHTML = "Número de vidas: "+ pacman_vidas;
}
pintaEcra();
}
The functions listed inside the code will only do matrix manipulation operations (nothing special really).
EDIT 3: As requested, here goes:
function reinicia_tabuleiro()
{
pacman_vidas = 3;
vidas.innerHTML = "Número de vidas: 3";
pontuacao.innerHTML = "Pontuação: 0";
pontos = 0;
for(i=1;i<24;i++)
{
for(j=1;j<24;j++)
{
if(tabuleiro[i][j] == 0)
tabuleiro[i][j] = 2;
}
}
}
Sorry dude, I don't see anything that would be causing this. What browser are you using? I'm doing similar tests on IE and FF and am getting window focus after clicking 'Ok' in the alert box. Have you tried using Firebug? It is a great program for debugging javascript. I would highly recommend it for this pacman project you are doing. You might have an error somewhere in your code that is causing this that isn't very apparent in the code shown above.
Well right now, I don't have solution to this problem but I have a workaround.
Dont use alertbox, use lightbox(div with higher z-index value) and make the div show and hide based on condition in javascript.
I hope this will help.
I just went through a similar problem with keydown and Firefox 5.0. The window focuses when the page loads and all my $(window).keydown(...) events worked fine.
Then after I show an alert, none of the events fire. It ends up that the window does not focus itself after I dismiss the alert. I was able to solve it by forcing the window to refocus when it blurs. I'm using jQuery so here's what it looks like for me:
$(window).blur(function(){
setTimeout(function(){
$(window).focus();
}, 0);
});
The timeout is necessary since Firefox (& maybe other browsers) won't let you immediately focus during a blur event.
This may have unintended consequences since you're basically never letting the window blur. For example, clicking on the location bar won't even work because the window pulls focus back immediately. To dig a deeper hole, you might set a "refocus" flag for your callback so it knows whether to give up focus or not. Here's the basic idea:
var doRefocusWindow = false;
$(window).blur(function(){
if(!doRefocusWindow) return;
doRefocusWindow = false;
setTimeout(function(){
$(window).focus();
}, 0);
});
...
doRefocusWindow = true;
alert("Game Over");

Prevent selecting & copying

I want to inactive selecting & copying text in html page.
when I used Javascript & inactive right click user can use Ctrl+V!!
You can't. Don't even try. Don't annoy your users.
If you put it publicly on the web, it can be copied. Technically, it already is copied as soon as the user sees it. As colithium pointed out, all the techniques can be circumvented. Heck, you can look at the source code. You can curl the raw data from the command line, no JS/IMG/layer hack can prevent that.
There is no full proof solution. You can play javascript games (easy to turn off). You can place invisible layers about the text so it can't be selected easily (easy to view source). You can use images instead of text (just bad).
While I agree in principle with the other posters that trying to do this may annoy the user, sometimes a manager or customer demands that this be done, and so an answer needs to be supplied.
Check out this page on www.dynamicdrive.com that will supply you with a few JavaScripts towards this end. Specifically see "Disable Text Select Script" and "No right click script".
Disable Text Select Script:
/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //IE route
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
target.style.MozUserSelect="none"
else //All other route (ie: Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
//Sample usages
//disableSelection(document.body) //Disable text selection on entire body
//disableSelection(document.getElementById("mydiv")) //Disable text selection on element with id="mydiv"
No right click script:
//Disable right mouse click Script
//By Maximus (maximus#nsimail.com) w/ mods by DynamicDrive
//For full source code, visit http://www.dynamicdrive.com
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")

Categories

Resources