开发者

Is there a way to detect find on the page searches in javascript

开发者 https://www.devze.com 2023-03-20 05:25 出处:网络
each browser has find on page f开发者_JAVA百科unctionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.Here is a solution which can account

each browser has find on page f开发者_JAVA百科unctionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.


Here is a solution which can account for alternative page find situations (ex. Command+F, '/' on Firefox). It checks for any of these keypresses and sets a timer when they occur. If the window is blurred soon after, then it is assumed that the Find dialog is showing.

Disadvantages: does not account for the "Find" dialog being launched via the menu. I don't see any way to be sure about this part, since (as far as I know, at least) browser UI is off-limits to Javascript running inside the DOM.

var keydown = null;

$(window).keydown(function(e) {
    if ( ( e.keyCode == 70 && ( e.ctrlKey || e.metaKey ) ) ||
         ( e.keyCode == 191 ) ) {
        keydown = new Date().getTime();
    }

    return true;
}).blur(function() {
    if ( keydown !== null ) {
        var delta = new Date().getTime() - keydown;
        if ( delta >= 0 && delta < 1000 )
            console.log('finding');

        keydown = null;
    }
});

jsFiddle, tested in Chrome, Safari and Firefox


You could do (to detect whenb a user press ctrl+f):

window.onkeydown = function(e){
   if(e.keyCode == 70 && e.ctrlKey){
    //user pressed ctrl+f
}

Fiddle here: http://jsfiddle.net/d8T72/


Of course you can try to hook into ctrl+f or cmd+f shortcut, but even if that works on "some" browsers, that way you only would know that an user pressed that shortcut and is most likely to search for something.

If the browser allows to overwrite that shortcut, you could further block the default behavior and implement your own search logic on the site. But that is considered most times as very bad practice. Overwritting native browser behavior is pretty pretty bad.

On the other hand, there is no "event" which gets triggered when a browser executed a search process. In short words, no, there actually is no way to detect or hook into a search process with javascript (if there is one, it's never gonna be cross browser compatible).


As initially suggested by @Nicola Peluchetti, here is a slightly improved version by feature sniffing:

window.onkeydown = function(e){
    var ck = e.keyCode ? e.keyCode : e.which;
    if(e.ctrlKey && ck == 70){
        alert('Searching...');
    }
}

Browser search test case »

0

精彩评论

暂无评论...
验证码 换一张
取 消