有没有办法检测在 javascript 中的页面搜索中的查找

2022-01-20 00:00:00 events find javascript

每个浏览器都有在页面上查找功能 (ctrl+F).有没有办法检测 javascript 中的用户搜索,以便我可以附加其他操作.

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.

推荐答案

当然可以尝试hook到ctrl+fcmd+f 快捷方式,但即使它适用于某些"浏览器,这样您也只会知道用户按下了该快捷方式并且最有可能搜索某些内容.

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.

另一方面,浏览器执行搜索过程时不会触发事件".简而言之,不,实际上没有办法使用 javascript 检测或挂钩搜索过程(如果有,它永远不会跨浏览器兼容).

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

相关文章