簡體   English   中英

我可以通過 JavaScript 以編程方式打開瀏覽器的本機搜索對話框嗎?

[英]Can I programmatically open the browser's native search dialogue by JavaScript?

是否可以從網頁內部以編程方式打開 Web 瀏覽器的本機搜索對話框?

更重要的是,如果可能的話,我可以以編程方式在其中執行搜索嗎?

無法使用 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>

如果您的意思是根據您的操作系統使用command + fctrl + f觸發的頁面內的瀏覽器搜索

你可以使用window.find()方法,這里是它的參考

否則,如果您指的是包含網站 URL 的搜索欄,您可以使用window.location.href訪問其值,該值將顯示當前 URL

如果你想做一些搜索,你可以通過輸入輕松地將其更改為任何內容

window.location.href = your_value;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM