5

Is it possible to know what my users are searching for on my web pages by Ctrl+F in JavaScript? So when a user uses Ctrl+F to search for something, JavaScript can capture this action (and the search phrase) and send it back to the server.

Possible? How?

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
datasn.io
  • 12,564
  • 28
  • 113
  • 154
  • Yes, it is possible. What specifically are you having trouble with? – Will C. Jan 07 '13 at 00:19
  • I don't know how. I searched in Google it's all triggering Ctrl + F key rather than to track it. – datasn.io Jan 07 '13 at 00:20
  • 1
    found via google: http://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery (replace S keycode with F). This can track the keystroke - tracking what they type in the search box is out of javascripts ability. – jbabey Jan 07 '13 at 00:21
  • Sorry, I can only go so far as getting the ctrl+f key strokes. Retrieving the text they are searching for in the browser is not possible. – Will C. Jan 07 '13 at 00:39

3 Answers3

1

Nope, not possible. On some browsers you can catch the key combination Ctrl+F, but you can't spy on what the user searched for. On other browsers you can't catch Ctrl+F at all.

If it's any consolation, there's probably a security flaw you can use on IE6.

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
jevakallio
  • 35,324
  • 3
  • 105
  • 112
1

No. You can't and by all security reasons should never have access to browser's UI elements outside page. You can capture Ctrl+F and handle it on your own though. But, of course, it will look different than browser's own UI element.

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
1

I've just found a workaround that might help in some cases.

Notice, that document and scrollable elements are always scrolling to the next searched occurrence - we can take advantage of that and create an "hidden" scrollable element and wait for it to scroll. When it scrolls you can then read the position to which it scrolled and get matched word.

http://jsfiddle.net/oz6gum90/6/

HTML:

<div id="hiddenScrollableContent">
    <div></div> <!-- first element must be empty -->
    <div>car</div>
    <div>cat</div>
    ...
</div>

CSS:

#hiddenScrollableContent{
    overflow: scroll;
    position:absolute;
    height:20px;  /* can't be zero ! */
    opacity:0.01; /* can't be zero ! */
    pointer-events: none;
}
#hiddenScrollableContent div{
    height: 100px;
}

JS:

$('#hiddenScrollableContent').scroll(function(e){
    var top = $(this).scrollTop();

    if (top==0)
        return; //prevents endless loop

    var index = Math.round(top / 100);
    var element = $('div', this).eq(index);
    var elementsText = element.text();
    $(this).scrollTop(0);

    console.log('top:'+top, 'index:'+index);

    $('span').text(elementsText);
});
cimak
  • 1,765
  • 3
  • 15
  • 18