Track visitor use of "Ctrl + F" on a website?
Yes, it's possible:
$(document).ready(function(){
ctrl = false;
document.addEventListener("keydown", function(e){
if(e.which == 17){
ctrl = true;
}
if(e.which == 70 && ctrl == true){
e.preventDefault();
}
}, true);
document.addEventListener("keyup", function(e){
if(e.which == 17){
ctrl = false;
}
});
});
And with .preventDefault()
we cancel the regular event.
But for the Command key I'm not sure what it is, some says that its e.metaKey
if you are using jQuery, because the problem is that the Command key don't have the same JavaScript key code on each browser, so you must handle it manually or jQuery can help you.
If you want to test it http://jsfiddle.net/a5t2q/
EDIT : You must click on the "Result" section to see that Ctrl+F is blocked, because that section is the one referred as "document" in this case.
If you want capture the event keyboard Ctrl + F and continue with the opening of the standard searchbox of the browser, you could do this:
var KEY_CTRL = 17;
var KEY_f = 70;
var isReserved = false;
var useExclusiveKeyEvent = false;
var isNewSearchEvent = false;
/*THIS VARIABLE IS RENDERED BY SERVER SIDE*/
var clientRandomKey = "78349DE472AA30032DE2DF344FF28374";
window.onkeyup=function(ev){
if(ev.which == KEY_CTRL){
isReserved=false;
}
}
window.onkeydown=function(ev){
//!IMPORTANT NOT MAKE UI DELAY IN THIS FUCTION
if(ev.which == KEY_CTRL) {
isReserved=true;
}
if((isReserved==true)&&(ev.which == KEY_f)) {
var currentDate = new Date();
console.log( "INTO EVENT FUNCTION >\n "+ currentDate+ " \n ID: "+clientRandomKey+"\n launch search a word");
isNewSearchEvent=true;
if(useExclusiveKeyEvent){
return false;}
}
}
window.setInterval(function(){
if(isNewSearchEvent){
isNewSearchEvent=false;
//TODO ajax send code
var currentDate = new Date();
var msg = "OUTSIDE EVENT FUNCTION >\n " + currentDate+ " \n ID: "+clientRandomKey+"\n launch search a word"
console.log(msg);
alert(msg);
}
},2500);
This is a live example.
As you can see in the example, when the user presses the right keyboard combination, event function sends a "log string"
in the console ("EVENT INTO FUNCTION"),
while changing the state of a flag(isNewSearchEvent
).
This flag is evaluated in a timer to send another "log string"
in the console ("OUTSIDE EVENT FUNCTION")
and open an alert with the same message.
This double passage is necessary because cannot create breaks into the event function, that should listen in a correct speed of capture.