我可以通过 JavaScript 以编程方式打开浏览器的本机搜索对话框吗?

use*_*751 11 javascript browser

是否可以从网页内部以编程方式打开 Web 浏览器的本机搜索对话框?

更重要的是,如果可能的话,我可以以编程方式在其中执行搜索吗?

ابن*_*آدم 7

无法使用 javascript打开浏览器的实用程序,例如查找、扩展、设置等。但是,您可以使用提示窗口创建自己的搜索:

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(" ");
  }
});
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)

您还可以使用window.find()在页面中查找字符串:

<!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>
Run Code Online (Sandbox Code Playgroud)


Muh*_*mdi 3

command如果您的意思是使用+fctrl+触发的页面内的浏览器搜索,f具体取决于您的操作系统

您可以使用该window.find()方法,这里是它的参考,

否则,如果您指的是包含网站 URL 的搜索栏,您可以使用window.location.href它将显示当前 URL 来访问其值

如果您想做一些搜索,只需输入即可轻松将其更改为任何内容

window.location.href = your_value;
Run Code Online (Sandbox Code Playgroud)

  • 在上面的评论中,OP 已经说过这不是他们想要的。 (3认同)