Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

How to simulate multiple keypress in JavaScript?

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>

Upvotes: 2

Views: 1113

Answers (1)

halfzebra
halfzebra

Reputation: 6797

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

Upvotes: 2

Related Questions