javascript - Alert when Browser/tab close detection - javascript

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+ :)

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

detect exit event in IE and Fireforx

I want to detect the exit event on all browser, I tried this code :
<html>
<head>
<script type="text/javascript">
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
</script>
</head>
<body>
<p>
Exit your browser ....
</p>
</body>
</html>
this code works in Chrome and safari but it it does'nt work in IE 11 and Fireforx 50.0.1 ... Any ideas ?
From the MDN page following notes are being mentioned
Note also, that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.
The hidden keys inside about:config can be found with the keys dom.disable_beforeunload and dom.require_user_interaction_for_beforeunload.
Your code seems fine for the rest, so it may help to look in your config files (The note mentions mobile browsers, however I have these settings on my Desktop browser as well)
Try with
window.addEventListener('beforeunload', function(evt){ ...
this is the response that I find, It work for me.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
thank you

Crash in chrome with input [type = file] / Drag and drop javascript jquery

After hours and hours of searching an answer to my issue I finally decided to come over you.
Here is the problem :
I have a really simple page with an input = file. And a zone for showing the image loaded.
On the other side I have a Jquery/javascript script which load the file and put it in the div with onChange method.
Two possibilities : the user selects the image in file explorer and then click ok. Or he leaves the file window without loading any file by clicking cancel or close.
In this case everything is fine
BUT the user also can try to drag the file from the file window to the div. But I don't want him to do that and I know how to prevent this. (Look at the code below)
And it works, nothing enter in the div and the browser doesn't redirect on a new page.
It's not necessary for Firefox and internet Explorer, only chrome gives the possibility to drag from intern file explorer of the browser.
Until this point, it's alright.
BUT after dragging if the user try to leave the files window (by clicking cancel / close or in loading a new file) then chrome completely crash. (It doesn't crash everytime, but 1 time for 3 tests) and to this point : the only possibility that remains is forcing the browser to close
Bug in image
And I really don't get why :/
I tried everything to get where the problem occurred with console.log .. but nothing happend before the crash. Not event the onchange() from the .js...
I also tried to do it with tiny file and the result is the same.
I think the bug is coming from Chrome browser but still, I can't let my website this way and I really need your help for this point.
My idea are :
closing the file Window after the user tried to drag something but it seems impossible in javascript to close something we didn't open by ourself
to make impossible to move or drag any file from the file window of the browser. Like it is in Firefox and Internet Explorer
or just find the reason of the crash but it seems impossible to realize.. Console.log issue no message. It just crashes..
I hope you'll be able to deal with it better than me. I really need help here,
Regards
The code :
jQuery(document).ready(function($) {
var loadFichier = $('#professionnal-icones-pictures-add'),
contenerImages = $('#imagesPro');
loadFichier.on('change', function(event) {
console.log("change");
event = event || window.event;
var fichierLoad = loadFichier[0].files[0],
output = document.getElementById('output1');
if (output.src == "") {
if (event.target.files[0]) {
var url = URL.createObjectURL(event.target.files[0]);
output.src = url;
}
}
});
window.addEventListener("dragover", function(e) {
e = e || event;
e.preventDefault();
e.stopPropagation();
}, false);
window.addEventListener("drop", function(e) {
e = e || event;
e.preventDefault();
e.stopPropagation();
}, false);
contenerImages.on(
'dragover',
function(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
}
)
contenerImages.on(
'dragenter',
function(e) {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
}
)
contenerImages.on(
'drop',
function(e) {
e = e || window.event;
if (e.originalEvent.dataTransfer) {
if (e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
}
}
}
);
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="/sitePerso/vue/profil/style-profil.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="professional-get-pictures">
<div id="contener-selection">
<div id="imagesPro">
<div>
<img id='output1' />
</div>
</div>
<div id="contener-icones-pictures">
<input id="professionnal-icones-pictures-add" type="file" accept="image/*">
</div>
</div>
</div>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="profiltest.js"></script>
</body>
</html>
I'm really surprised this issue led to any comment. This crash is still occuring on so many websites with chrome.
Still, I finally found one way to resolve this problem. It doesn't tell me why it was crashing on chrome (if one of you knew, I would be so glad to hear it). But it prevents the browser from crashing and it still stays comfortable for the user.
I added these two lines, in this way, the user really can't drag / drop anything from the file explorer :
var dt = e.originalEvent.dataTransfer;
dt.effectAllowed = dt.dropEffect = 'none';
So this :
contenerImages.on(
'dragover',
function(e) {
e= e|| window.event;
e.preventDefault();
e.stopPropagation();
}
)
$(window).on(
'dragover',
function(e) {
e= e|| window.event;
e.preventDefault();
e.stopPropagation();
}
)
Become this :
contenerImages.on(
'dragover',
function(e) {
e= e|| window.event;
e.preventDefault();
e.stopPropagation();
var dt = e.originalEvent.dataTransfer;
dt.effectAllowed = dt.dropEffect = 'none';
}
)
$(window).on(
'dragover',
function(e) {
e= e|| window.event;
e.preventDefault();
e.stopPropagation();
var dt = e.originalEvent.dataTransfer;
dt.effectAllowed = dt.dropEffect = 'none';
}
)
Perhaps someone found a better answer but I hope this post could help a lot of people.
The only problem with this is : it prevents the user from dragging from the file explorer as well (and not only from the file window of the browser). But I guess you'll find a way to deal with it.
I just make a summary of the problem for future readers : when I dragged file(s) from the internal file window of the browser (only chrome), and then tried to close it : it often brought this one to crash.
Have a good day everyone :)

how to stop page redirect

I need to stop all the page redirection through javascript.
I have some script which will redirect the page to some other location.
How can I stop all the page redirection on my page through jquery or javascript.
You can stop the redirect by doing the following.
<script language="JavaScript" type="text/javascript">
//<![CDATA[
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
//]]>
</script>
Not sure if all browsers support this but that should do the trick.
If I'm understanding you correctly, you need to stop users navigating away from the page?
If so, Marcos Placona's answer is one part of it - although all what you actually need is:
$("a").click(function(e) { e.preventDefault(); });
You also don't want people to hit F5 I'm guessing? Well that's harder. Preventing defaults on key press, cross-browser is horrible. But a couple of codes that work in some browser are below here:
function disableF5() { // IE
document.onkeydown = function() {
if (window.event && window.event.keyCode == 116) { // Capture and remap F5
window.event.keyCode = 505;
}
if (window.event && window.event.keyCode == 505) { // New action for F5
return false; // Must return false or the browser will refresh anyway
}
}
}
function disableF5v2() { // FIREFOX
$(this).keypress(function(e) {
if (e.keyCode == 116) {
e.preventDefault();
return false;
}
});
}
However, the cross-browser issue can partly be solved with -
window.onbeforeunload = function(e) {
var message = "Your confirmation message goes here.", e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
Hope that all helps anyway. The last bit of code is from another question on this site here.
Rob
Are you trying to stop an iframe breaker? Something like:
<script language="JavaScript" type="text/javascript">
<!--
function breakout_of_frame()
{
if (top.location != location) {
top.location.href = document.location.href ;
}
}
-->
</script>
If so, you can not.
If it's only redirects through link clicks, in jQuery you can do this:
$(".someClass a").unbind('click');
if it's an existing page redirect, you'll need to give us some more information about what kind of redirect this is, so we can help further.
Hope this helps you
AFAIK this won't be possible, since page redirection can occur in many ways. He can click on an anchor tag, can submit a form with different action, set window.location to another page on button click and invoke server code to redirection.
And you won't be able to detect many of these.

How do I disable right click on my web page?

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

Categories

Resources