Disabling the Browser Context Menu
You can disable the browser context menu for an element in your DOM with the following JavaScript recipe:
function disableContextMenu(element) {
element.oncontextmenu = function() {
return false;
}
}
For example, to disable the context menu over a photo on your page, you could use:
disableContextMenu(document.getElementById("photo"));
Browsers like Firefox do not always allow web pages to disable the context menu (this option is a setting in Firefox), so this recipe will not work 100% of the time in all browsers.





Comments
So nope, dont do it, ever.
Truly, it is annoying when someone "disables" your context menu so that you don't steal their content (yeah, right), but when building an AJAX web application, it really comes in handy - a requirement, if you want to acheive the complete look-and-feel of a standard non-web application.
Press+Hold LeftButton
Press RightButton
Release LeftButton
Release RightButton
I don't think disabling the context menu is a great idea. There are situations where you want to replace the context menu with one you have made yourself, but you should at least allow the original context menu through some other combination, say ctrl-RightClick.
This was one of the first options I ticked when I started using firefox.
a) no way to prevent "theft" of images
b) no way to effectively prevent context menus due to different browsers, javascript options, userscripts, script blockers etc etc...
So please don´t even try to disable context menus. If you don´t want your content to be copied, then the only way is to not publish it at all.
Kinda like the old saying you can fool some of the people some of the time but you can never fool all the people all the time.
And how would you link the image in the DB? just from the clean air, or putting base64encoded mime string into the src attribute? You are not able to that and you don't have a clue what you are talking about, so don't comment in future on topic you don't understand.
The only way is to check the referer in the image script linked and if no referer is passed, stop the execution or display default place holder image. This still however won't be 100% defense against stealing of images, as anyone can even save image generated by script etc.
The main purpose of this debate is not to block user from saving the image, but to develop application that handles the right click in the way user is accustomed to.
Ofcourse it's possible to upload images or any other binary data to ur database (i've done it on oracle and db2, haven't tried it on mysql yet), it all comes down to dbms. Oracle and it's plSQL (and oracle web agent) make it possible to retrieve the binary data (blob) and use it as a src within your html elements. Oracle and IBM both have predefined routines and rewrite rules that help you link to them. No need to reinvent hot water.
Ah ha ha ha!! Take your own advice buddy! Storing images in a database is easy.
One method is how Ap4rTheAd mentioned.
Another method is to create a php script that will retrive the image data, and output it on a page with the proper image headers.
Know it all douchebags like that give me a good chuckle from time to time. :)
Anyone know how they do it?
~d
The Prototype.js framework (http://en.wikipedia.org/wiki/Prototype_Javascript_Framework) will successfully suppress the context menu. Just include the prototype.js script, and add something like this onload:
Event.observe(document,'contextmenu',disableContextMenu,false);
function disableContextMenu(evt) {
alert("I won't allow the context menu!");
Event.stop(evt);
}
This does not work in every browser. EG in Konqueror it doesn't. But what does Google do to get this effect?
Google also stopped tha Drag&Drop Effect...
It seems that certain versions of Konqueror/Safari do not work with Prototype's Event.stop() method. Here is a short article describing the problem: http://particletree.com/notebook/eventstop/
Solution 3 apparently works for this guy, but I have no way of testing it out at the moment.
document.onmousedown = hide;
document.oncontextmenu = new Function("return false");
put this in your javascript file. it will block the context menu for IE. for firefox just use this CSS for your
body, html{
-moz-user-focus: ignore;
-moz-user-select: none;
}
the aim i think is not to stop people from getting yo code but to make the web application better simulate a real win32 one. lol
document.onmousedown = hide;
document.oncontextmenu = new Function("return false");
put this in your javascript file. it will block the context menu for IE. for firefox just use this CSS for your
body, html{
-moz-user-focus: ignore;
-moz-user-select: none;
}
the aim i think is not to stop people from getting yo code but to make the web application better simulate a real win32 one. lol
But none of this is anything to do with disabling menus in Javascript, anyway - there are still other legitimate reasons for doing that.
Although this might not work in all browsers, it is a very important point, and something all good developers should be aware of.
YAHOO.util.Event.addListener(document.getElementById("myElement"), "contextmenu", doSomething);
function doSomething(event)
{
//insert your own context menu script here
YAHOO.util.Event.stopEvent(event);
}
document.oncontextmenu = function () {
return false;
}
I'll let you implement that how you will for your web 2.0 application projects...such as detecting what element you are over, stopping propagation, selecting the appropriate return value 'true|false'...
:-)
<html>
<head>
<script type="text/javascript">
window.onload = context_menu;
function context_menu () {
document.oncontextmenu = function ( event ) {
if ( typeof event == 'undefined' ) {
event = window.event;
}
if ( typeof event.target == 'undefined' ) {
event.target = event.srcElement;
}
var node = event.target;
do {
if ( typeof eval( node.getAttribute('rel') ) == 'function' ) {
eval( node.getAttribute('rel') )( node );
return false;
}
} while ( node = node.parentNode );
return true;
}
}
function menu1 ( node ) {
// do your custom menu 1 here //
alert( 'context menu one: ' + node.id );
}
function menu2 () {
// do your custom menu 2 here //
alert( 'context menu two' );
}
</script>
</head>
<body>
<div>
<ul>
<li rel="menu1" id="one"><a href="#">Some Nav One</a></li>
<li rel="menu1" id="two"><a href="#">Some Nav Two</a></li>
<li rel="menu1" id="three"><a href="#">Some Nav Three</a></li>
<li rel="menu1" id="four"><a href="#">Some Nav Four</a></li>
</ul>
</div>
<img rel="menu2" src="http://technology.beloblog.com/archives/Wootlogo.gif" />
</body>
</html>
On another note, it is indeed possible to completely eliminate "hotlinking" and the forced download of images using PHP. To eliminate hotlinking, all you have to do is check the referrer when you retrieve an image from the database (if it's not your site, just output a "no hotlinking" image, or text). To disable users "right clicking" or "viewing source" in order to download, simply make each image unique using some manipulation of the current unix timestamp. Give each user a sessionID, then create a database that logs the time at which each and every page was loaded for each sessionID. If the user tries to access an image by entering it's url, it would be seen that the sessionID's last page load was NOT within the same ~10 seconds that the image was loaded. Depending on the speed of your web server, you can choose to reduce the time to something smaller - thus making it impossible to download an image that you choose to "protect".
But, as someone mentioned above, that's a lot of work just to find out that someone else's "image downloader" hack might just be a little quicker than your server.
- You need to learn XHTML. Google it, use it.
-you should make sure to reserve the "window.onload" event for other scripts, so you don't break any pages:
window.myOnLoadOld = window.onload?window.onload:function(){};
window.onload = function() {
window.context_menu();
window.myOnLoadOld();
};
-When you define a function with the syntax you have used ( var = function(){}; ) you need to add a semicolon after the terminating brace bracket. You can see what I mean above ^
My interest in the context menu is to expand navigation options on certain elements on a web application I'm building.
About image protection, I know of no reliable way to disable the browser caching the image on the local machine. I have also written simple browser 'robots' that can download images and ignore Pragma rules.
It is also easy enough for someone to navigate to a page, then disable javascript in the browser, then use the context menu to download the image off the page.
There is NO sure way that I know of to protect images...if they are worth that much then put a watermark on them.
Cheers
http://www.engjazzband.com/gallery/
Well, I guess we'll just have to let Apple work out DRM for web images (haha).
However, to own up to all the things I still don't know, why is the purpose of the closing semi-colon for anonymous functions? I've seen it but never run into any issues with using or not using it. I guess if you consider the function the value of the variable then it makes perfect sense in a 'strict' sense. So never mind, I get it--thanks for the feedback.
Cheers
To increase browser compatibility, you need to do more than "return false":
function preventMe(e) {
if(!e) e=window.event;
if(e.returnValue)
e.returnValue = false;
if(e.preventDefault)
e.preventDefault();
return false;
};
document.oncontextmenu = preventMe;
window.oncontextmenu = preventMe;
document.onmousedown = preventMe;
window.onmousedown = preventMe;
---
That will make the script work as intended on *a few* more browsers. I still think disabling the context menu is a waste of energy though.
Another thought on image protection - the browser would "uncache" an image if it's content-expiry was set very very low, right?
The purpose of the semicolon after declaring an anonymous function is because it is actually a standard JavaScript variable. The "function" keyword does not define a variable in the traditional sense, thus no semicolon is required.
Only a few JavaScript engines will throw an exception if you don't include the semicolon, and they are all outdated (I believe old Netscape does this).
If you are interested in learning more about this kind of stuff, check out this forum:
http://www.jasonmillerdesign.com/forum/
Look at the Cellnotes.ca API.
good, I was never one for the window.addEventListener route, it reminds me too much of Visual Basic.
Once the image is loaded by the browser it can no longer be protected.
If you want to protect an image you are trying to sell, then load a low-res thumbnail or a version with a watermark. Then people who pay to get the good one can have a download key sent to them or loaded on the page, and you can deliver the high-res image out of a database--or something on those lines.
I was in the works on building an image editor using JavaScript and PHP so a person could scale (resize-constrained), resize, crop, and compress (jpeg) an image .
I thought this would be useful for uploading images to a site database but be able to edit them on the page in a simple fashion.
I put that script on hold for a while, while I'm working on an app for a friend.
Let me know if you want anyone to brainstorm with for your image sharing app. Sometimes a different perspective can be useful.
Cheers,
Kevin (kdouglas AT satarah DOT com)
The functionality I have planned would be:
-draw lines, boxes, circles, and pencil on photos
-save an edited photo to the database
-Add text to a photo (imgString, I believe)
-overlay images on an existing photo
It's going to be VERY AJAX intensive, but I think it might appeal to a lot of people.
My personal issue with drawing tools is that the lines are always jaggedy unless they allow for vector curves between two points. If you can find a way to soften the pencil lines or allow for other brush types (air brush) application then it sounds like a cool idea.
Email me (above address) if you want to talk some more.
admin [at] jasonmillerdesign [dot] com
or post a message on my forum, at:
www.jasonmillerdesign.com/forum
As for a JavaScript AJAX object, I would be interested in what yours looks like. I started working with AJAX before I was doing ObjectOriented JavaScript design, so my AJAX library is likely getting outdated.
i can steal any image from any webpage :)
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function preventMe(e) {
if(!e) e=window.event;
if(e.returnValue)
e.returnValue = false;
if(e.preventDefault)
e.preventDefault();
return false;
};
function enableMe(e) {
if(!e) e=window.event;
if(e.returnValue)
e.returnValue = true;
if(e.preventDefault)
e.preventDefault();
return true;
};
function handleMouseDownEvents(e) {
if (!e) var e = window.event;
if (e.srcElement.id == 'bodyArea')
{
document.oncontextmenu = preventMe;
}
else
{
document.oncontextmenu = enableMe;
}
return;
}
document.onmousedown = handleMouseDownEvents;
</script>
</head>
<body id="bodyArea">
testing...... <input name="box1" type="text"> <input name="box2" type="text">
</body>
</html>
I found this page while looking for a way to guarantee that my context menu on my web browser on *MY* computer is not overridden by some obnoxious web developer. Some code has been by passing my "do not allow disabling or replacing of the context menu" setting. (My next step is to kill the interpreter all together.)
The number one reason I use Firefox is because there is nothing I find more annoying when visiting a web page than not being able to right-click and open-link-in-new-tab. I used get VERY angry when this happened and just avoid the offending website all together.
So let me ask you control freaks masquerading as web developers a question...
What gives you the right to dictate what menus are allowed to pop up on *MY* computer? I read above where it's to protect your 'content'. (images) Well, I have an idea for you then: Do not place materials you do not want others to consume on a device called a 'server'. Because what a server does by it's very nature is distribute information. Not to mention the fact that the servers you guys use are on a public network.
All messing with the context menu does is really miff people like me off. Even if you disabled every menu in the browser there is still a key combination that will get your pictures: <ALT> + <PRINT/SC>
So, just like movie and music companies, all your attempts at introducing 'rights management' to your content does is anger legitimate users. So, do the world a favor and don't impose your OCD on other people...
Chad
And if you want to show a customized context menu you have to disable the default one.
Write a Comment