I am trying to capture the terms people search on my website(after CTRL+F). Is there a way to get what's actually being searched in javascript? Or the my option is to redirecting CTRL+F to focus/use a customized input?
-
I don't think so, this is purely client side. – roottraveller Feb 21 '19 at 04:51
2 Answers
From this answer
So basically you can detect if user click Ctrl + F
then continue to detect the
search term.
window.addEventListener("keydown",function (e) {
# maybe you can add more detect for mac (Command + F)
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
# now detect all the key code here until "Enter"
# then you have the search term
}
})

- 2,742
- 16
- 20
There is no browser API that lets you know if a user is doing a "find" on a page. The closest thing might be the Selection API to detect when a user is making a selection, however, browsers don't necessarily select or focus what they've found, they only highlight it and scroll the page to the element.
Trying to intercept the built in browser capabilities is typically frowned upon. However, what it sounds like is you want to add a hotkey for your site search. You can listen for keyboard input on the document using vanilla Javascript, or, if you want to add multiple hotkeys, use one of many hotkey libraries. In either case, when the hotkey is is pressed, simply focus the search input.
window.addEventListener('keydown', function(e) {
// check if ctrl (or cmd on osx) + shift + F is pressed
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.keyCode === 70) {
// TODO: change the ID on your search box
document.getElementById('my-search-box').focus()
}
})

- 88,194
- 49
- 192
- 260
-
The OP doesn't seem to want to add a hotkey for their site's search bar. They want to know when you ctrl-f for the term "pickles" *in the page*. Like, when you use the usual browser built-in ctrl-f, and search for "pickles", they want to identify that action. Possibly they are A/B testing or something, and want to get data on user behavior. – Him Nov 20 '22 at 17:10