Searching Body Text with textRange: Enter the Gecko - The first function
(Page 2 of 4 )
Again, you’ll need two functions, each mapped to its respective button in the HTML file. The first function does the searching:
function textSearch() {
button1clicked = 1
searchWord = prompt("Please enter a word to search for", "", "Search");
if (searchWord == "") || (searchWord == null)) {
return false
}
match = window.find(searchWord, false, false, false, true, false, false);
if (match == false) {
window.alert("Couldn't find '" + searchWord + "'");
}
}
As you can see, the button1clicked flag is still set, which enables us to handle the second button being clicked prior to the first button. A variable is then set to hold the input captured by a prompt box. The first of the prompt objects takes a descriptive string, the second parameter is a value that can be placed in the input box on the prompt by default, but is not needed in this example. The final parameter specifies the prompt box title. When you run the script, you’ll see that the title of the prompt box will also contain the text [JavaScript application] which is part of the chrome architecture (also a core part of Mozilla based browsers) and therefore cannot be removed.
The first if statement checks that an empty string hasn’t been retuned for a value of ‘null’, which would occur if the cancel button on the prompt was selected, and alerts the user as necessary. The second if statement produces an appropriate alert if match is equal to false, meaning that the body text did not contain an instance of the search word.
Sandwiched comfortably between the if staments, the match variable is set to true or false depending on the result of the find method that is applied to the window object. This method is intelligent enough to know that you are searching for text within the text of the window. This method takes a hefty seven parameters, which control how the search is performed; the first parameter is the string to search for. The rest are as follows: caseSensitive, searchBackwards, wrapAround, wholeWord, searchInFrames, and showDialog, the functions of which, I’m sure, are fairly obvious. The last parameter there, the showDialog boolean value, actually controls a built-in text finder/replacer; if you set this to true, however, the rest of your code will still execute and the built-in text dialog will remain hanging around after ours has finished.
As you can see, there are no references to ranges of any kind and no code which controls the highlighting of words matched against the search word. This is handled automatically by the browser. All in all, this is a lot simpler than the IE specific code.
Next: The second function >>
More Code Examples Articles
More By Dan Wellman