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?
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>
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With