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

前端 未结 4 570
栀梦
栀梦 2020-11-30 12:26

each browser has find on page functionality (ctrl+F). Is there a way to detect user searches in javascript so that I could attach additional actions.

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 13:19

    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

提交回复
热议问题