Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I programmatically open the browser's native search dialog by JavaScript?

Is it possible to programmatically open the web browser's native search dialogue from inside a web page?

And more over, if it's possible, can I programmatically perform a search inside of it?

like image 204
user7607751 Avatar asked Oct 16 '18 12:10

user7607751


2 Answers

There is no way to open browser's utilities like find, extensions, settings, etc using javascript. However, you can create your own search with the prompt window:

const searchBtn = document.getElementById("searchBtn");
const searchElement = document.querySelector("#text"); // Any element you want to search
const backup = searchElement.innerHTML;

searchBtn.addEventListener("click", function () {
  searchElement.innerHTML = backup;

  const search = prompt("Search");
  const text = searchElement.innerHTML.split(" ");

  if (search != null) {
    for (let i = 0; i < text.length; i++) {
      let index = text[i];
      let splitIndex = index.split("");
      if (index.toLowerCase().includes(search.toLowerCase())) {
        for (let si = 0; si < index.length; si++) {
          if (search.toLowerCase().includes(index[si].toLowerCase())) {
            splitIndex[si] = `<mark>${index[si]}</mark>`;
            text[i] = splitIndex.join("");
          }
        }
      }
    }
    searchElement.innerHTML = text.join(" ");
  }
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Search Menu</title>
  </head>
  <body>
    <p id="text">The quick brown fox jumped over the lazy dog.</p>
    <button id="searchBtn">Search</button>
  </body>
</html>

You can also use window.find() to find a string in your page:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Search Menu</title>
  </head>
  <body>
    <p id="text">The quick brown fox jumped over the lazy dog.</p>
    <button id="searchBtn">Search</button>
  </body>

  <script type="text/javascript">
    const searchBtn = document.getElementById("searchBtn");

    searchBtn.addEventListener("click", function () {
      const search = prompt("Search");
      const searchResult = window.find(search);
    });
  </script>
</html>
like image 121
ابن آدم Avatar answered Oct 23 '22 19:10

ابن آدم


if you mean the browser search inside the page that's triggered using command + f or ctrl + f depending on your OS

you can use the window.find() method and here is a reference for it,

otherwise, if you mean the search bar which contains the URL of the website you can access its value by using window.location.href which will present the current URL

and if you want to do some search you can easily change it to anything just by typing

window.location.href = your_value;
like image 39
Muhammad Hamdi Avatar answered Oct 23 '22 19:10

Muhammad Hamdi