faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

36 of 45 people (80%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How to capture CTRL button press both in IE & NN ?

Apr 4th, 2008 21:18
ha mo, Mark Filipak, Manoj S.N.,


My answer assumes you mean CTRL key, rather than button.
/////////////////////////////////////////////////////////
//
// NETSCAPE-STYLE PROPAGATE DOWN EVENT ARCHITECTURE
//
if (window.captureEvents)
  {
  window.captureEvents(Event.KEYDOWN)
  }
window.onKeyDown =
  function (e)
    {
    if (e.modifiers==2)
      {
      ...call to your local CTRL key handler goes here...
      return false // assumes you want to kill it
      }
    else return true
    }
//
/////////////////////////////////////////////////////////
//
// MICROSOFT-STYLE BUBBLE UP EVENT ARCHITECTURE
//
document.onkeydown = // assumes not handled at lower level
  function ()
    {
    if (event.ctrlKey)
      {
      event.cancelBubble = true // assumes you want to block it
      event.returnValue = false // assumes you want to kill it
      ...call to your local CTRL key handler goes here...
      return false // assumes you want to kill it
      }
    else return true
    }
//
/////////////////////////////////////////////////////////
Netscape Navigator propagates the event to the window object first and 
thus, to this code. Internet Explorer on the other hand propagates the 
event to the target of the event first, and it bubbles up from there to 
this document level code.
Note that some people test for document.layers (to detect NN) and 
document.all (to detect MSIE), but I don't. I think that making use of a 
major architecturual feature of the browser (propagate down vs bubble 
up), which is very unlikely to be changed in the future, produces more 
durable code -- what if Microsoft implements layers in the future?
Now to the larger issue. If you want to capture the CTRL key so a surfer 
can't see or save your javascript, the code above, by itself, will not 
do it unless you are running a signed script. Your handler must instead, 
take the focus from away from the event object (window or document). 
which causes the event to die. Popular ways to do this are:
  alert("Sorry. This function has been disabled.") // or
  window.opener.focus() // or focus to any other window.
Assuming that the larger picture is what you are interested in, you 
simply can't stop a determined hacker from getting your client side 
javascript. What is download to the surfer's computer can be caught 
before the browser gets it using commonly available tools (don't ask!).
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com