How to quickly and universally re-enable scrolling on a website that has disabled scrolling with JavaScript? (Given that there is actually content to scroll through)
The scrolling works when JavaScript is disabled and with JavaScript enabled.
window.scrollBy(0, 100) works fine but not when bound to any key or mouse scroll.
In a browser like Chrome etc.:
Inspect the code (for e.g. in Chrome press ctrl + shift + c);
Set overflow: visible on body and/or html element (for e.g., <body style="overflow: visible">)
Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).
Just thought I would help somebody with this.
Typically, you can just paste this in console.
$("body").css({"overflow":"visible"});
Or, the javascript only version:
document.body.style.overflow = "visible";
Edit: Joshua Goldberg's code from a comment reply:
I found a similar, bookmarkletable script that did work in this very helpful QA answer that did:
var r="html,body{overflow:auto !important;}";
var s=document.createElement("style");
s.type="text/css";
s.appendChild(document.createTextNode(r));
document.body.appendChild(s);
void 0;
adding overflow:visible !important; to the body element worked for me.
You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 90) {
window.scrollBy(0, 100)
}
if (evtobj.keyCode == 65) {
window.scrollBy(0, -100)
}
}
document.onkeydown = KeyPress;
Select the Body using chrome dev tools (Inspect ) and change in css overflow:visible,
If that doesn't work then check in below css file if html, body is set as overflow:hidden , change it as visible
One last thing is to check for Event Listeners > "scroll" and test deleting them.
Even if you delete the Javascript that created them, the listeners will stick around and prevent scrolling.
With Chrome, one way to automatically re-enable scrolling on a website is to download the Tampermonkey extension, then add this script (click "Install this script").
In general, if you have a URL for a script where the URL ends in .user.js and have Tampermonkey installed, you can paste it into Chrome's Omnibox to install the script. More ways to install scripts with Tampermonkey can be found here.
Try this:
window.onmousewheel = document.onmousewheel = null
window.ontouchmove = null
window.onwheel = null
Try ur code to add 'script' is last line or make test ur console (F12) enable scrolling
<script>
(function() {
for (div=0; div < document.querySelectorAll('div').length; div++) {
document.querySelectorAll('div')[div].style.overflow = "auto";
};
})();
</script>
Important things to know about overflow
overflow-x: hidden; means can't scroll using horizontal (left to right) axis.
overflow-y: hidden; means can't scroll in vertical (up and down) axis.
overflow: hidden; you can't scroll neither vertical nor horizontal.
This could be another way, based on #Future Sim answer
addEventListener('wheel', (event) => {
window.scrollBy(0, event.deltaY);
});
Just paste it and you will be able to use your mouse wheel
What worked for me was disabling the position: fixed; CSS.
Related
Can I disable right click on my web page without using JavaScript? I ask this because most browsers allow user to disable JavaScript.
If not, how do I use JavaScript to disable right click?
You can do that with JavaScript by adding an event listener for the "contextmenu" event and calling the preventDefault() method:
document.addEventListener('contextmenu', event => event.preventDefault());
That being said: DON'T DO IT.
Why? Because it achieves nothing other than annoying users. Also many browsers have a security option to disallow disabling of the right click (context) menu anyway.
Not sure why you'd want to. If it's out of some misplaced belief that you can protect your source code or images that way, think again: you can't.
DON'T
Just, don't.
No matter what you do, you can't prevent users from having full access to every bit of data on your website. Any Javascript you code can be rendered moot by simply turning off Javascript on the browser (or using a plugin like NoScript). Additionally, there's no way to disable the ability of any user to simply "view source" or "view page info" (or use wget) for your site.
It's not worth the effort. It won't actually work. It will make your site actively hostile to users. They will notice this and stop visiting. There is no benefit to doing this, only wasted effort and lost traffic.
Don't.
Update: It seems this little topic has proven quite controversial over time. Even so, I stand by this answer to this question. Sometimes the correct answer is advice instead of a literal response.
People who stumble on this question in hopes of finding out how to create custom context menus should look elsewhere, such as these questions:
Making custom right-click context menus for my web-app, which relies on jQuery
How to add a custom right-click menu to a webpage, which uses pure javascript/html
The original question was about how to stop right-click given that the user can disable JavaScript: which sounds nefarious and evil (hence the negative responses) - but all duplicates redirect here, even though many of the duplicates are asking for less evil purposes.
Like using the right-click button in HTML5 games, for example. This can be done with the inline code above, or a bit nicer is something like this:
document.addEventListener("contextmenu", function (e){
e.preventDefault();
}, false);
But if you are making a game, then remember that the right-click button fires the contextmenu event - but it also fires the regular mousedown and mouseup events too. So you need to check the event's which property to see if it was the left (which === 1), middle (which === 2), or right (which === 3) mouse button that is firing the event.
Here's an example in jQuery - note that the pressing the right mouse button will fire three events: the mousedown event, the contextmenu event, and the mouseup event.
// With jQuery
$(document).on({
"contextmenu": function (e) {
console.log("ctx menu button:", e.which);
// Stop the context menu
e.preventDefault();
},
"mousedown": function(e) {
console.log("normal mouse down:", e.which);
},
"mouseup": function(e) {
console.log("normal mouse up:", e.which);
}
});
So if you're using the left and right mouse buttons in a game, you'll have to do some conditional logic in the mouse handlers.
If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).
However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.
If you are a jquery fan,use this
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
First, you cannot achieve this without using a client side capability. This is where the javascript runs.
Secondly, if you are trying to control what an end user can consume from your site, then you need to rethink how you display that information. An image has a public url that can be fetched via HTTP without the need for a browser.
Authentication can control who has access to what resources.
Embedded watermarking in images can prove that the image was from a specific person/company.
At the end of the day, resource management is really user/guest managment.
The first rule of the Internet, if you dont want it taken, dont make it public!
The second rule of the Internet, if you dont want it taken, dont put it on the Internet!
If your goal is to disallow users to simply save your images, you can also check if the clicked target is an image, only disable right click in that case. So right click can be used for other purposes. Taken from the code above:
document.addEventListener("contextmenu", function(e){
if (e.target.nodeName === "IMG") {
e.preventDefault();
}
}, false);
This is just to take away the easiest way of saving your images, but it can still be done.
If your aim is to prevent people being able to download your images, as most people have said, disabling right click is pretty much ineffective.
Assuming you are trying to protect images the alternative methods are -
Using a flash player, users can't download them as such, but they could easily do a screen capture.
If you want to be more akward, make the image the background of a div, containing a transparent image, à la -
<div style="background-image: url(YourImage.jpg);">
<img src="transparent.gif"/>
</div>
will be enough to deter the casual theft of your images (see below for a sample), but as with all these techniques, is trivial to defeat with a basic understanding of html.
You cannot accomplish what you're asking without using Javascript. Any other technology you may choose to use can only help to compose the web page on the server side to be sent to the browser.
There simply is no good solution, and there is no solution period without Javascript.
If you just want to disable right click for saving images on the web page, go with this CSS solution:
your-img-tag {
pointer-events: none;
}
Before Implemented On Same Image:
After Implemented On Same Image:
Tested working in both Chrome and Firefox.
Just do this
write oncontextmenu on body tag
<body oncontextmenu="return false">
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('img').bind('contextmenu', function(e){
return false;
});
});//]]>
</script>
</head>
<body>
<img src="http://www.winergyinc.com/wp-content/uploads/2010/12/ajax.jpg"/>
</body>
Simple Way:
<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Do it like below (It works on firefox too):
$(document).on("contextmenu",function(e){
if( e.button == 2 ) {
e.preventDefault();
callYourownFucntionOrCodeHere();
}
return true;
});
I had used this code to disable right click in any web page, Its working fine. You can use this code
jQuery(document).ready(function(){
jQuery(function() {
jQuery(this).bind("contextmenu", function(event) {
event.preventDefault();
alert('Right click disable in this site!!')
});
});
});
<html>
<head>
<title>Right click disable in web page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
You write your own code
</body>
</html>
Of course, as per all other comments here, this simply doesn't work.
I did once construct a simple java applet for a client which forced any capture of of an image to be done via screen capture and you might like to consider a similar technique. It worked, within the limitations, but I still think it was a waste of time.
Put this code into your <head> tag of your page.
<script type="text/javascript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
This will disable right click on your whole web page, but only when JavaScript is enabled.
<script>
window.oncontextmenu = function () {
console.log("Right Click Disabled");
return false;
}
</script>
Try This
<script language=JavaScript>
//Disable right mouse click Script
var message="Function Disabled!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>
Disabling right click on your web page is simple. There are just a few lines of JavaScript code that will do this job. Below is the JavaScript code:
$("html").on("contextmenu",function(e){
return false;
});
In the above code, I have selected the tag. After you add just that three lines of code, it will disable right click on your web page.
Source: Disable right click, copy, cut on web page using jQuery
There are three most popular following ways of disabling a right mouse click on your webpage.
#1 Using HTML Body Tag
<body oncontextmenu="return false;">
#2 Using CSS
body {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
-o-user-select: none;
user-select: none;
}
#3 Using JavaScript
document.addEventListener('contextmenu', e => e.preventDefault());
I know I am late, but I want to create some assumptions and explainations for the answer I am going to provide.
Can I disable right-click
Can I disable right click on my web page without using Javascript?
Yes, by using JavaScript you can disable any event that happens and you can do that mostly only by javaScript. How, all you need is:
A working hardware
A website or somewhere from which you can learn about the keycodes. Because you're gonna need them.
Now lets say you wanna block the enter key press here is the code:
function prevententer () {
if(event.keyCode == 13) {
return false;
}
}
For the right click use this:
event.button == 2
in the place of event.keyCode. And you'll block it.
I want to ask this because most browsers allow users to disable it by Javascript.
You're right, browsers allow you to use JavaScript and javascript does the whole job for you. You donot need to setup anything, just need the script attribute in the head.
Why you should not disable it?
The main and the fast answer to that would be, users won't like it. Everyone needs freedom, no-one I mean no-one wants to be blocked or disabled, a few minutes ago I was at a site, which had blocked me from right clicking and I felt why? Do you need to secure your source code? Then here ctrl+shift+J I have opened the Console and now I can go to HTML-code tab. Go ahead and stop me. This won't add any of the security layer to your app.
There are alot of userful menus in the Right Click, like Copy, Paste, Search Google for 'text' (In Chrome) and many more. So user would like to get ease of access instead of remembering alot of keyboard shortcuts. Anyone can still copy the context, save the image or do whatever he wants.
Browsers use Mouse Navigation: Some browsers such as Opera uses mouse navigation, so if you disable it, user would definitely hate your User Interface and the scripts.
So that was the basic, I was going to write some more about saving the source code hehehe but, let it be the answer to your question.
Reference to the keycodes:
Key and mouse button code:
http://www.w3schools.com/jsref/event_button.asp
https://developer.mozilla.org/en-US/docs/Web/API/event.button (would be appreciated by the users too).
Why not to disable right click:
http://www.sitepoint.com/dont-disable-right-click/
Try this code for disabling inspect element option
jQuery(document).ready(function() {
function disableSelection(e) {
if (typeof e.onselectstart != "undefined") e.onselectstart = function() {
return false
};
else if (typeof e.style.MozUserSelect != "undefined") e.style.MozUserSelect = "none";
else e.onmousedown = function() {
return false
};
e.style.cursor = "default"
}
window.onload = function() {
disableSelection(document.body)
};
window.addEventListener("keydown", function(e) {
if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 67 || e.which == 70 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {
e.preventDefault()
}
});
document.keypress = function(e) {
if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 70 || e.which == 67 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {}
return false
};
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == 123 || e.keyCode == 18) {
return false
}
};
document.oncontextmenu = function(e) {
var t = e || window.event;
var n = t.target || t.srcElement;
if (n.nodeName != "A") return false
};
document.ondragstart = function() {
return false
};
});
$(document).ready(function () {
document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
});
Important Note: It depends on browser and OS to allow such prevention or not!
Should you do it? No. Because it will not prevent the user, but it will just annoys him/her.
Can you use it? Yes. Examples: In some web-apps where you want to have customized pop-up menu, in-game where users might be annoyed when mistakenly they right-click, and other cases.
Chrome (v65) in Ubuntu 16.04 = You CAN disable right-click.
Chrome (v65) in Mac OS 10.11 = You CAN NOT disable right-click.
Chrome (v65) in Windows 7 = You CAN NOT disable right-click.
Firefox (v41) in Mac OS 10.11 = You CAN disable right-click.
Firefox (v43) in Windows 7 = You CAN disable right-click.
// Vanilla JS way
document.addEventListener('contextmenu', function(e){
e.preventDefault();
});
// jQuery way
$(document).bind('contextmenu', function(e) {
e.preventDefault();
});
A few things to consider:
Browser Plugins like "enable right click" in the chrome store exist for a reason, and you wont be able to get around them. There is LITERALLY NOTHING you can do to stop people from downloading your content as they literally have to download it to even see it in their browser anyway; People try but its always out there.
In general, if content shouldn't be public, don't put it online.
Also, not being able to right click is an accessibility issue and amounts to unlawful discrimination against the blind or disabled or elderly in many cases. Check you local laws, but in the USA its actively against the law in the form of the Federal ADA as the blind or the elderly who may have vision issues are a legally protected class.
So instead of doing this and wasting a lot of time and effort, don't even bother trying to do this. It could just get your company sued or have them fail a compliance audit.
Yes, you can disable it using HTML and Javascript.
Just add oncontextmenu="return false;" on your body or element.
It is very simple and just uses valid HTML and Javascript, no jQuery.
Javascript:
document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false");
I'd like to add a note (for chrome 97) not sure if this is a bug related to chrome or my environment.
Right clicking on a specific element of my application opens a page in a new tab, using mousedown and oncontextmenu="return false" I was still having the contextual menu appearing, even on the new opened page (Only the menus of installed chrome extensions appear on that contextual menu, I think this "bug" should get fixed in future version of the browsers).
But in the meantime I fixed it using this simple hack
function onMouseDown () {
setTimeout(() => window.open('the link', '_blank'), 100)
}
I am just deferring the tab opening. I think this bug occurs because the right click is caught by the new opened page, not from the original page of my application that tries to open the tab.
Hope it saves you from headaches.
Use this function to disable right click.You can disable left click and tap also by checking 1 and 0 corresponding
document.onmousedown = rightclickD;
function rightclickD(e)
{
e = e||event;
console.log(e);
if (e.button == 2) {
//alert('Right click disabled!!!');
return false; }
}
I've been working on a project for work where I need to create a Javascript "jump-menu" within a page.
(Q:Wait, a jump-menu? Why don't you just use a elements and namespaces to navigate within your page?
A: Because that would defeat the purpose! So please, don't provide answers like that. I need to do this with Javascript (AND I'M NOT USING JQUERY!!!))
So, here is what I do:
I make a list at the top of the page, and a list at the bottom of the page.
I add an event listener to each list item at the top of the page and I attach a reference to that list items corresponding content item within the page.
When the link at the top is clicked, I grab to offsetTop of the item I want to scroll to, and I set either the document.body.scrollTop or the window.pageYOffset.
I've never actually needed the window.pageYOffset, but somewhere told me it would work and I never removed it from my code. Either way, this appears to work with the document.body.scrollTop in Chrome, Safari, and Opera, yet it doesn't work in Firefox or IE. Why?
Here is the code block where I set the document.body.scrollTop:
if(elem.jump_ref)
{
if(document.body.scrollTop || document.body.scrollTop === 0)
{
document.body.scrollTop = elem.jump_ref.offsetTop - page_top_padding;
}
else if(window.pageYOffset || window.pageYOffset === 0)
{
window.pageYOffset = elem.jump_ref.offsetTop - page_top_padding;
}
}
And Heres The Project In JSFIDDLE
I've stepped through and found that "Yes, I am grabbing the right element." and "Yes, I am setting the document.body.scrollTop, and "No, I am not setting the document.body.scrollTop to zero." and yet it still doesn't work! Please help! My webpage is supposed to go public on Tuesday!
Well, I believe I have found my answer. So far, it appears to work in Chrome, Firefox, IE, Opera, and Safari (these were the only ones I was able to test). I don't know what type of mobile support this feature will have (if any), but my page already has an entirely different functionality for mobile anyway.
Either way, here's the fix. Its the window.scrollTo method!:
this.jump = function(evt)
{
var elem = evt.srcElement || evt.currentTarget;
var page_top_padding = 100;
if(elem.jump_ref)
{
window.scrollTo(0, (elem.post_ref.offsetTop - page_top_padding));
}
}.bind(this);
And like I said, it works great in nearly everything! Everything except JSFiddle. lol. I don't quite get it, but luckily no one is going to be visiting my webpage in JSFiddle.
I discovered a problem that seems to reproduce always when opening a piece of html and javascript in IE8.
<html>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(window).resize(function() {
console.log('Handler for .resize() called');
});
});
</script>
<div id="log">
</div>
</body>
</html>
Loading this file in IE8 and opening Developer Tools will show that the log message is printed continuously after one resize of the browser window.
Does anyone has an idea why? This is not happening in IE7 or IE9, nor in other browsers (or at least their latest versions).
UPDATE
One solution to prevent the continuos trigger of resize() is to add handler on document.body.onresize if the browser is IE8.
var ieVersion = getInternetExplorerVersion();
if (ieVersion == 8) {
document.body.onresize = function () {
};
}
else {
$(window).resize(function () {
});
}
But this does not answer my question: is the continuous firing of resize() a bug in IE8?
If "show window contents while dragging" is switched on, you will be inundated with resize events. I guess you're testing IE8 on a separate Windows machine which has this effect enabled (Display Properties -> Appearance -> Effects...).
To counteract this, you can wrap & trap the resize events to tame them: http://paulirish.com/demo/resize
This article says Chrome, Safari & Opera suffer from this too.
I only see the issue you are describing if an element on the page is resized (as described in this question). Your example doesn't work for me, but I assume for you it is appending the console message in the log div that you have there, which means that it is resizing the div and triggering the window resize event.
The answer that Lee gave is correct, but the method in the link didn't work for me. Here's what I did:
var handleResize = function(){
$(window).one("resize", function() {
console.log('Handler for .resize() called');
setTimeout("handleResize()",100);
});
}
handleResize();
This way, the handler is unbound as soon as it fires, and is only re-bound after you've finished all your actions that might re-trigger a page resize. I threw in a setTimeout to provide additional throttling. Increase the value in case your scripts need more time.
I have a weird problem.
I try to write a GreaseMonkey script to be run in Firefox and Google Chrome.
With Chrome I tried 2 extensions : "TamperMonkey" and "Blank Canvas Script Handler", mainly because my script check regulary for a new version on an external site and this is considered as cross site scripting and not authorized in Chrome.
To show you my problem, I write a simple test case :
// ==UserScript==
// #name test
// #namespace http://fgs.ericc-dream.fr.nf
// #description test gm script
// #include http://gaia.fallengalaxy.eu/
// #author ericc
// #version 0.0.1
// ==/UserScript==
/* We attach an event listener to the body tag and trigger the function
* 'message' each time that an element is inserted in the page */
var el = document.body;
el.addEventListener('DOMNodeInserted', message, false);
var extraFlag = false;
function message(event) {
/* first we capture the id of the new inserted element
* (the one who created the event) */
var objId = event.target.id;
/* add an event listener on the map container */
if (objId == "extra") {
el = document.getElementById('extra');
el.addEventListener('DOMSubtreeModified',readTest,false);
GM_log(el.style.display);
}
}
function readTest() {
el = document.getElementById('extra');
GM_log(extraFlag);
GM_log(el.style.display);
if ((el.style.display != 'none') && (!extraFlag)) {
alert('extra');
extraFlag = true;
} else if ((el.style.display == 'none')) {
extraFlag = false;
}
}
the div element 'extra' is modified by the page. The problem is that Chrome is unable to read the value of el.style.display and thus extraFlag never become 'false' again.
I use this flag to avoid to run the code several time, the site is heavily JavaScript driven
This code work nicely in Firefox !
I tried to search with Google but can't find a correct answers. Seems easy to change the value of display, but it seems that I'm the only one who try to read it !!!
I write this code because "DOMAttrModified" isn't supported in Chrome :-(
Thanks in advance for your help
ericc
I'm having a hard time understanding exactly what your question is, but it looks like Chrome can read .style.display properties just fine. I just threw the following code into an HTML template and loaded it in Chrome 10:
<div id="div1">
</div>
<div id="div2" style="display: block;">
</div>
<div id="div3" style="display: inline;">
</div>
<div id="div4" style="display: none;">
</div>
<script type="text/javascript">
alert(document.getElementById("div1").style.display);
alert(document.getElementById("div2").style.display);
alert(document.getElementById("div3").style.display);
alert(document.getElementById("div4").style.display);
document.getElementById("div1").style.display = "none";
alert(document.getElementById("div1").style.display);
</script>
The code produced 5 'alert' boxes with the following output:
blockinlinenonenone
So it seems Chome reads this property just fine.
Maybe the issue is that the webpage on which you're running your greasemonkey script is behaving differently in Chrome than in Firefox? Could it be that the ID of the element is different, or the element is being removed from the DOM instead of just being hidden? What would happen if you modified your function with some more checks, kinda like this?
function readTest() {
el = document.getElementById('extra');
if(el)
{
GM_log(extraFlag);
GM_log(el.style.display);
if (el.style.display && (el.style.display != 'none') && (!extraFlag)) {
alert('extra');
extraFlag = true;
} else if ((el.style.display == 'none') || !el.style.display) {
extraFlag = false;
}
}
else
{
GM_log(extraFlag);
GM_log("element not present");
extraFlag = false;
}
}
Does that help? If not, is there any other reason you could think of why el.style.display wouldn't evaluate properly in Chrome?
It might help if we knew more about what you're trying to do with your script, and possibly what web page or code you're trying to run this on.
After several hours and a ton of test case, I finally find an acceptable explanation (but not yet a solution !)
Let's explain the scenario :
1°) the user click on an icon on the screen
2°) the div#extra, which is already present in the page, is made visible by removing its display property (.style.display="")
3°) the div#extra is filed by an AJAX function with some elements depending on which icon was clicked by the user (more than 200 elements in certain case)
4°) the user click on an other icon to close the div
5°) all elements from the div#extra are removed
6°) the div#extra is hidden by putting is display property to 'none' (.style.display="none")
At first, on Firefox, I used "DOMAttrModified" event on the div#extra to check when the display property was modified and react accordingly.
Problem, this event is not supported on Chrome !!
So I replace it by "DOMSubtreeModified" (attached to div#extra) which is supported by both browser .... but not exactly in the same way :-(
On Firefox, an event is fired for every modification in the subtree but also when the element itself is modified.
On Chrome, they are a little bit more strict and fired event only for modification in the subtree .... and this is my issue !
In Firefox,first event is fired at point 2 (in the scenario) and last at point 6 allowing my function to read when the div#extra is made hidden
In Chrome, first event is fired at point 3 and last at point 5 ... so when the the div#extra is hidden my function is not called and I can't modify the flag !!!! CQFD
Now, or I will add an event listener to the body of the page to intercept when the display property is modified, but it will generate a lot of call to my function, or the developer of TamperMonkey said yesterday that his extension now support "DOMAttrModified" (on Chrome) ....
Thanks anyway to take the time to understand my question and your proposed solution
ericc
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; }
}