【问题标题】:Can I programmatically open the browser's native search dialog by JavaScript?我可以通过 JavaScript 以编程方式打开浏览器的本机搜索对话框吗?
【发布时间】:2018-10-16 12:31:01
【问题描述】:

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

此外,如果可能的话,我可以通过编程方式在其中执行搜索吗?

【问题讨论】:

  • @epascarello,不,window.find() API 是另一回事。我在询问您手动单击 Ctrl + F 时显示的本机搜索栏
  • 我指的不是window.find,我只是想弄清楚你想要什么。对我来说,本地搜索是当您“命令 + 选项 + F”并使用浏览器搜索时。不是内置的查找对话框 (COMMAND + F)。
  • 这在stackoverflow上被问了很多次,答案是。真的没有办法触发它。该方法有一个显示对话框的参数,但似乎没有浏览器真正支持它。

标签: javascript browser


【解决方案1】:

有no way to open browser's utilities 像使用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(" ");
  }
});
<!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>

您也可以使用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>

【讨论】:

  • 有趣的方法。但它似乎不起作用:尝试“searchResult”,它会说“No results found”。另外,有没有办法让搜索结果像原生搜索一样突出显示(例如 Chrome 中的黄色突出显示)?
  • @brillout 我编辑了答案。检查新代码。
【解决方案2】:

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

您可以使用window.find() 方法,这里有一个reference,

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

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

window.location.href = your_value;

【讨论】:

  • 在 OP 上面的 cmets 中已经说过这不是他们想要的。
  • 赏金作者在这里:我知道window.find(),但我想要(以及 OP)是通过 JavaScript 触发浏览器搜索对话框。
  • @brillout 我不清楚谷歌/网络搜索对话框是 OP 所说的。根据 OP 对该问题的评论之一:“我在询问您手动单击 Ctrl + F 时显示的本机搜索栏”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 2015-08-17
相关资源
最近更新 更多