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

前端 未结 4 554
栀梦
栀梦 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 12:55

    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).

    0 讨论(0)
  • 2020-11-30 13:01

    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/

    0 讨论(0)
  • 2020-11-30 13:07

    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 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题