2

I am trying to bring up the browser search from a link click.

I found there are some functions like window.find(), but they don't work with all browsers. So the best way to achieve this is, simulate ctrl + f.

I have this following code, but this is not working, I don't know why.

function bringUpSearch() {

  var keyboardEvent = document.createEvent("KeyboardEvent");
  var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


  keyboardEvent[initMethod](
    "keydown", // event type : keydown, keyup, keypress
    true, // bubbles
    true, // cancelable
    window, // viewArg: should be window
    true, // ctrlKeyArg
    false, // altKeyArg
    false, // shiftKeyArg
    false, // metaKeyArg
    102, // keyCodeArg : unsigned long the virtual key code, else 0
    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
  );
  document.dispatchEvent(keyboardEvent);
}
<a href="#" onclick="bringUpSearch()">Bring up browser search</a>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
  • possible duplicate of [Simulate JavaScript Key Events](http://stackoverflow.com/questions/596481/simulate-javascript-key-events) – Ben N Jul 20 '15 at 16:29
  • You can find answer here : http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once – Nicolas D Jul 20 '15 at 16:33
  • @BenN I want to bring up browser search (ctrl + f) from a link click, what's wrong here https://jsfiddle.net/biki636/Lf7rd7u0/1/ – Soumitri Pattnaik Jul 20 '15 at 16:39

1 Answers1

2

You can't do that in Chrome, since there is no API for that. See the list of Chrome Extensions Documentation

In those ancient manuscripts people mention Find Dialog: window.find(), that you were able to open the dialog, by passing true as the last argument, but it's not supported for ages.

What you can is to make a custom search textfield, grab the user input from it and run window.find

halfzebra
  • 6,771
  • 4
  • 32
  • 47
  • This script does not work in any browser, so it's not Chrome only, I want to know what's the problem with this script – Soumitri Pattnaik Jul 20 '15 at 17:18
  • @SoumitriPattnaik I have updated my answer, it seems like back in times there were an option to open a dialog. Not anymore! – halfzebra Jul 20 '15 at 17:23