Thursday, May 31, 2007

How to prevent right-click with JavaScript

I have searched the web for this solution. I dont' remember where I found it but here is. This code disables right-click through JavaScript. Place it in the "head" section of your web page. The code works with Internet Explorer and Firefox.

<script language="javascript">

var isNS = (navigator.appName == "Netscape") ? 1 : 0;

if(navigator.appName == "Netscape")

document.captureEvents(Event.MOUSEDOWNEvent.MOUSEUP);

function mischandler( )
{ return false; }

function mousehandler(e)

{

var myevent = (isNS) ? e : event;

var eventbutton = (isNS) ? myevent.which : myevent.button;

if((eventbutton==2)(eventbutton==3))
return false;

}

document.oncontextmenu = mischandler;

document.onmousedown = mousehandler;
document.onmouseup = mousehandler;

</script>



Refer your friends to this blog:
http://programmingcentral.blogspot.com/

16 comments:

Anonymous said...

I've never understood why authors/owners/coders want to prevent someone from right-clicking on a web page... It doesnt really prevent anyone from getting to the source, or copying text/images.

And so many useful features of a browser are conveniently located via a right-click (black, reload, preferences, ad-block, bookmark page, etc.) that it ends up being, IMO, more of an irritation than anything else.

Can anyone give me some insight as to why some people do this?

Anonymous said...

I dont' think its about preventing web site visitors from viewing the source code or copying images.

A useful application of this script would be to prevent vistors from refreshing a page that is the result of a form "post"

I imagine this script could be very effective in a popup window with all "features" disabled (i.e, no statusbar, addressbar, etc...)

Anonymous said...

hhhmmm... I would argue then that your UI is flawed. Users only occasionally "accidentally" hit refresh. If they are refreshing, then there is a REASON they feel the need to. Maybe they arent sure their information was received?

If you dont want them hitting refresh after posting, then have your script send a header to the browser to redirect them to a landing page via a standard GET. That way if they hit refresh, they are only refreshing the landing page, not the form submission.

beyond that, there is still the F5 button (and the javascript to disable that only works in IE), and the context-menu button on the keyboard that would allow them to refresh.

I'm still searching for an example of when this would truly be useful....

Joe said...

Gilzow,

You make some valid points. It is a good idea to redirect visitors to a "confirmation" page after a form has been submitted.

However, let's say that validation must be performed on the server-side rather than the client side. In this scenario, a page would post information back to itself. If error messages are returned, it would be a good idea to prevent vistors from refreshing the page since this action would incur an unnecessary server round trip.

I know that some people will say that validation should occur only on the client side. Yet, there are instances when this is not possible (such as logging in to create a session)

Anonymous said...

no, i dont mean a confirmation page; a landing page. also, validation should ALWAYS occur on the server-side. you can do some validation on the client side, but that same validation should occur again on the server-side. the client can NEVER be trusted. If you rely on client-side validation only, then you have just opened yourself up to an attack.

Even if the form had errors, you can still use a landing page. After processing the post, store the values in your session, store a list of those errors in the session, add a query value to the redirected URL, and then have your script for that page input the errors into the HTML before the form. This way, if the user hits refresh, all they are doing is refreshing the page via GET.

but it brings me back to my original point: WHY are the users hitting refresh? Are they not aware that there was an error and that's why they are trying to refresh the page?

A philosophy I adopted when I first started coding was to guide users through the application instead of trying to control or dictate to them what I want them to do. Build the app so that from the application side, they cant do the things you dont want.

Anonymous said...

gilzow,

Very insightful. The client-side code is not enough for validation.
An individual with less than savory intentions may decide to "post" values to your remote script (SQL injection and the rest of it...)

However, let's say that there's a page that pulls a lot of information from a database.

We wouldn't want people constantly hitting refresh and affecting the performance of the web server.

Anonymous said...

ok, I can understand reducing the trips to the db. But I dont think disabling the right-click is really the proper way to go about it. That's like using a car for a door stop: waaaay overkill. And you've only disable one method to accomplish a refresh. The user could still click the refresh button on the browser, or hit the F5 key.

To reduce the load, simply cache the results, and, as I said earlier, redirect to a landing page. That way if the user hits refresh, they arent re-posting AND you can pull the db results from cache instead of making another trip to the db server.

I'm still looking for a logical, reasoned explanation as to why one would ever NEED to disable the right mouse button on a page...

Mindmajick said...

Very helpful... always wanted to know how to do this.

Joe said...

gilzow,

In a previous post, I discussed the code to prevent page refreshes by way of the F5 key.

Imagine this: the content that you want to display is in a pop-up with all window features disabled. F5 refresh and right-click are both disabled.

I believe that the developer should have some control over his application.

There is yet one reason to prevent right-click. You may not want your visitors to back out to the previous page (which may be a transactional page that has expired). Expiration messages are annoying. Since your content is in a popup window with all features disables, web site vistors will not be able to back out either with the mouse or keyboard.

In the interest of making web applications more robust and flexible, I'd prefer that they function more like desktop apps.

Refer your friends to this blog:
http://programmingcentral.blogspot.com/

Anonymous said...

But the code to disable the F5 key only works in IE. And as far as having your results in a pop-up, most browsers pop-up blockers are (most likely) going to block it. Especially those spawned by javascript (which the one in your example would have to be).

[quote]
Since your content is in a popup window with all features disables, web site vistors will not be able to back out either with the mouse or keyboard.
[/quote]

You are incorrect. Lets say the user is using IE, the pop-up is allowed, and you have disabled the right-click and all other window features. They can STILL hit the backspace key on the keyboard OR use the context-menu key on the keyboard and go back. And that's assuming that the user hasnt disabled javascript, or parts of it. Let alone discussing the situation if the user is using something besides IE. Firefox and Opera both allow you to override what javascript is allowed to do. All browsers that support tabs (including IE7) allow the end user to force all pop-ups into a tab with all features still enabled. So the days of being ABLE to develop what you are describing is numbered. Why do you think NoScript is one of the top downloaded firefox entensions? ;)

Again, you have to ask yourself WHY are they wanting to go back. Or WHY are they wanting to refresh. If you look honestly, it is most likely a UI design flaw.

[quote]
I believe that the developer should have some control over his application.
[/quote]

ah, but remember: when you are dealing with web apps, you really have NO control over the client. The ONLY control you have is on the server side of things.

Joe said...

gilzow,

I'm glad you brought the issue of other browsers into the discussion. I hadn't thought of that (considering IE's market share).

You are right in stating that JavaScript can be disabled in IE and Firefox. You are also correct in stating that modern browsers allow clients to manage what JavaScript is able to do.

However, I disagree with you regarding the ability to back out to the previous page. I still believe this is a valid reason to disable right-click. Expiration messages from the browser are annoying. Currently, I place server-side and client-side expiration headers.

gilzow, please respond to this post with an email address so that I may invite you to be an author on this blog. I think you have alot of insights to contribute.


Refer your friends to this blog:
http://programmingcentral.blogspot.com/

Anonymous said...

you can reach me at

gilzow [remove-me] AT [remove-me] missouri.edu

Joe said...

gilzow,

I have invited you as an author to this blog.


Refer your friends to this blog:
http://programmingcentral.blogspot.com

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Anonymous said...

Do You interesting how to [b]Buy Viagra per pill[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Buy Viagra per pill[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/viagra%2C%20tramadol%2C%20zithromax%2C%20carisoprodol%2C%20buy%20cialis/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also you can find on our sites.
Generic [url=http://viagra.deutafilm.ru]buy generic viagra online in canada[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]cialis cialis genuinerx net viagra
viagra after cabg
Viagra Or Similar
viagra manchester po box
Viagra In Kolkata
viagra studies
edinburgh uk viagra news comment moo
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

Anonymous said...

Who can know and tell what goods are sold on this plat: [url=http://lacgotesa.chez.com]here[/url]
Thanks for the treatment of waiting!