简体   繁体   English

通过 JavaScript 跟踪 Ctrl + F 的使用?

[英]Tracking the use of Ctrl + F by JavaScript?

Is it possible to know what my users are searching for on my web pages by Ctrl + F in JavaScript?是否可以通过 JavaScript 中的Ctrl + F了解我的用户在我的网页上搜索的内容? 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.因此,当用户使用Ctrl + F进行搜索时,JavaScript 可以捕获此操作(以及搜索短语)并将其发送回服务器。

Possible?可能的? How?如何?

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.某些浏览器上,您可以捕获组合键Ctrl + F ,但您无法窥探用户搜索的内容。 On other browsers you can't catch Ctrl + F at all.在其他浏览器上,您根本无法捕捉Ctrl + F。

If it's any consolation, there's probably a security flaw you can use on IE6.如果有任何安慰的话,您可能会在 IE6 上使用安全漏洞。

No. You can't and by all security reasons should never have access to browser's UI elements outside page.不可以。出于所有安全原因,您不能访问页面外的浏览器 UI 元素。 You can capture Ctrl + F and handle it on your own though.不过,您可以捕获Ctrl + F并自行处理。 But, of course, it will look different than browser's own UI element.但是,当然,它看起来与浏览器自己的 UI 元素不同。

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/ http://jsfiddle.net/oz6gum90/6/

HTML: HTML:

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

CSS: 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: 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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM