Javascript: Buscar texto en la página cargada
01 de Mayo de 2007 en Javascript, Html, Programación
Lecturas: 15,336

BuscarA veces se hace necesario realizar una búsqueda sobre el texto mostrado por pantalla. En esta situación, No hay query de SQL que valga, ni procesos PHP, porque la página ya está generada y cargada en el navegador del cliente. Me interesaba realizar un sistema de búsqueda dónde el cliente, una vez cargada la página, pudiera buscar algo ahí sin recargar nada.

Estuve buscando una forma de solucionarlo y caí en una página que utiliza un conjunto de funciones Javascript que presenta una ventana de tipo prompt, realiza una búsqueda sobre lo mostrado en la página y resalta en un color específico las coincidencias.

A continuación posteo el código y lo comento un poco.

He recogido las funciones en un archivo .js, descargable desde aquí: Archivo .JS. Así es más fácil integrarlo en cualquier página, usando la conocida forma de incluir bibliotecas de funciones de Javascript en HTML:

HTML:
  1. <script language="javscript" />

Si abrimos el archivo nos encontramos un código como éste:

JAVASCRIPT:
  1. /*
  2. * This is the function that actually highlights a text string by
  3. * adding HTML tags before and after all occurrences of the search
  4. * term. You can pass your own tags if you'd like, or if the
  5. * highlightStartTag or highlightEndTag parameters are omitted or
  6. * are empty strings then the default  tags will be used.
  7. */
  8. function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
  9. {
  10. // the highlightStartTag and highlightEndTag parameters are optional
  11. if ((!highlightStartTag) || (!highlightEndTag)) {
  12. highlightStartTag = "<font style="color: blue; background-color: yellow">";
  13. highlightEndTag = "</font>";
  14. }
  15. // find all occurences of the search term in the given text,
  16. // and add some "highlight" tags to them (we're not using a
  17. // regular expression search, because we want to filter out
  18. // matches that occur within HTML tags and script blocks, so
  19. // we have to do a little extra validation)
  20. var newText = "";
  21. var i = -1;
  22. var lcSearchTerm = searchTerm.toLowerCase();
  23. var lcBodyText = bodyText.toLowerCase();
  24. while (bodyText.length> 0) {
  25. i = lcBodyText.indexOf(lcSearchTerm, i+1);
  26. if (i <0) {
  27. newText += bodyText;
  28. bodyText = "";
  29. } else {
  30. // skip anything inside an HTML tag
  31. if (bodyText.lastIndexOf(">", i)>= bodyText.lastIndexOf("<", i)) {
  32. // skip anything inside a <script /> block
  33. if (lcBodyText.lastIndexOf("/script>", i)>= lcBodyText.lastIndexOf("
  34. newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
  35. bodyText = bodyText.substr(i + searchTerm.length);
  36. lcBodyText = bodyText.toLowerCase();
  37. i = -1;
  38. }
  39. }
  40. }
  41. }
  42. return newText;
  43. }
  44. /*
  45. * This is sort of a wrapper function to the doHighlight function.
  46. * It takes the searchText that you pass, optionally splits it into
  47. * separate words, and transforms the text on the current web page.
  48. * Only the "searchText" parameter is required; all other parameters
  49. * are optional and can be omitted.
  50. */
  51. function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
  52. {
  53. // if the treatAsPhrase parameter is true, then we should search for
  54. // the entire phrase that was entered; otherwise, we will split the
  55. // search string so that each word is searched for and highlighted
  56. // individually
  57. if (treatAsPhrase) {
  58. searchArray = [searchText];
  59. } else {
  60. searchArray = searchText.split(" ");
  61. }
  62. if (!document.body || typeof(document.body.innerHTML) == "undefined") {
  63. if (warnOnFailure) {
  64. alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
  65. }
  66. return false;
  67. }
  68. var bodyText = document.body.innerHTML;
  69. for (var i = 0; i <searchArray.length; i++) {
  70. bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  71. }
  72. document.body.innerHTML = bodyText;
  73. return true;
  74. }
  75. /*
  76. * This displays a dialog box that allows a user to enter their own
  77. * search terms to highlight on the page, and then passes the search
  78. * text or phrase to the highlightSearchTerms function. All parameters
  79. * are optional.
  80. */
  81. function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
  82. {
  83. // This function prompts the user for any words that should
  84. // be highlighted on this web page
  85. if (!defaultText) {
  86. defaultText = "";
  87. }
  88. // we can optionally use our own highlight tag values
  89. if ((!textColor) || (!bgColor)) {
  90. highlightStartTag = "";
  91. highlightEndTag = "";
  92. } else {
  93. highlightStartTag = "";
  94. highlightEndTag = "";
  95. }
  96. if (treatAsPhrase) {
  97. promptText = "Please enter the phrase you'd like to search for:";
  98. } else {
  99. promptText = "Please enter the words you'd like to search for, separated by spaces:";
  100. }
  101. searchText = prompt(promptText, defaultText);
  102. if (!searchText)  {
  103. alert("No search terms were entered. Exiting function.");
  104. return false;
  105. }
  106. return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
  107. }
  108. /*
  109. * This function takes a referer/referrer string and parses it
  110. * to determine if it contains any search terms. If it does, the
  111. * search terms are passed to the highlightSearchTerms function
  112. * so they can be highlighted on the current page.
  113. */
  114. function highlightGoogleSearchTerms(referrer)
  115. {
  116. // This function has only been very lightly tested against
  117. // typical Google search URLs. If you wanted the Google search
  118. // terms to be automatically highlighted on a page, you could
  119. // call the function in the onload event of your  tag,
  120. // like this:
  121. //
  122. //var referrer = document.referrer;
  123. if (!referrer) {
  124. return false;
  125. }
  126. var queryPrefix = "q=";
  127. var startPos = referrer.toLowerCase().indexOf(queryPrefix);
  128. if ((startPos <0) || (startPos + queryPrefix.length == referrer.length)) {
  129. return false;
  130. }
  131. var endPos = referrer.indexOf("&amp;", startPos);
  132. if (endPos <0) {
  133. endPos = referrer.length;
  134. }
  135. var queryString = referrer.substring(startPos + queryPrefix.length, endPos);
  136. // fix the space characters
  137. queryString = queryString.replace(/%20/gi, " ");
  138. queryString = queryString.replace(/\+/gi, " ");
  139. // remove the quotes (if you're really creative, you could search for the
  140. // terms within the quotes as phrases, and everything else as single terms)
  141. queryString = queryString.replace(/%22/gi, "");
  142. queryString = queryString.replace(/\"/gi, "");
  143. return highlightSearchTerms(queryString, false);
  144. }
  145. /*
  146. * This function is just an easy way to test the highlightGoogleSearchTerms
  147. * function.
  148. */
  149. function testHighlightGoogleSearchTerms()
  150. {
  151. var referrerString = "http://www.google.com/search?q=javascript%20highlight&amp;start=0";
  152. referrerString = prompt("Test the following referrer string:", referrerString);
  153. return highlightGoogleSearchTerms(referrerString);
  154. }

En él, identificamos las siguientes funciones:

  • doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
  • highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
  • searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
  • highlightGoogleSearchTerms(referrer)
  • testHighlightGoogleSearchTerms()

doHighlight

Esta función busca el texto en el cuerpo de la página y, de encontrarlo, encierra la coincidencia entre un tag añadido setando el resaltado de la coincidencia. Se puede especificar qué tag de apertura y cierre será el que se use para resaltar la coincidencia.

highlightSearchTerms

Esta función separa (siempre que el segundo parámetro sea false) el string del criterio de búsqueda en espacios y llama a la función anterior para cada subcriterio. Si el segundo parámetro es true tratará el string como un único criterio, despreciando las coincidencias de las palabras que forman dicho criterio.

searchPrompt

Esta función presenta una ventana dónde introducir el criterio de búsqueda, y lo enviará a la función anterior para realizar el trabajo.

highlightGoogleSearchTerms

Esta función recoge el referer de la página y lo parsea. Trata de encontrar el criterio de búsqueda en Google que se ha introducido para mostrar la página de resultados de Google a través de la que el usuario ha entrado en nuestra página. Con el criterio identificado, llama a la función highlightSearchTerms para efectuar el resaltado de las coincidencias.

Necesita modificar el tag de la página, pues debe analizar el referer directamente al cargal la página.

testHighlightGoogleSearchTerms

Esta función simplemente es una forma rápida de testear la función anterior.

----

Como vemos, la funcion que realiza el trabajo es la primera, y las dos siguientes son funciones que añaden funcionalidad. Las dos últimas estan bién pero para realizar un "buscador" en la página no las necesitamos.

Podéis verlo funcionando en la sección de Letras de Canciones de LaDragonera.com

Tag:
 Enviar a Fresqui

Leer los Comentarios

[ # 959 ] Pingback desde La Dragonera » L’atac dels referers extranys! :: Informatica, Motos, Lletres de Cançons [10 de Mayo de 2007, 09:45]

[…] www.onlyporsche.net (buscar texte en pàgina cargada) […]

[ # 973 ] Comment desde Rodrigo [11 de Mayo de 2007, 02:42]

Me gusto,voy a probar en mi pagina porque la busqueda que tengo solo me funciona en IExplorer y no la he podido transformar para que tambien me la tome Firefox.

grax por el aporte.

Xauz ;)

[ # 974 ] Comment desde Xavi [11 de Mayo de 2007, 08:35]

De nada hombre. Si necesitas ayuda ya sabes ;)

[ # 3232 ] Comment desde Andrés [01 de Agosto de 2007, 09:29]

Muy buena la referencia.
El problema que tengo en este momento es con los acentos. Es decir necesito que tanto la búsqueda como el resaltado de las palabras encontradas no sea sensible a acentos o ñ.

¿alguna sugerencia?

Muchas gracias.

[ # 3263 ] Comment desde Xavi [02 de Agosto de 2007, 10:10]

Hola.

Puedes pasarle una regular expression para que limpie de acentos y carácteres extendidos el texto a buscar una vez el usuario lo haya introducido, y también en el texto de la página web, por ejemplo en la función highlightSearchTerms justo después de llenar la variable bodyText.

Un saludo

[ # 31520 ] Comment desde Hola [08 de Agosto de 2008, 10:32]

hola, como inserto el codigo en mi pagina html?

[ # 31770 ] Comment desde Xavi [11 de Agosto de 2008, 07:49]

Copia todo el código Javascript en un archivo nuevo y llámalo loquesea.js, y desde la página web llámalo con {script language=”javascript” src=”loquesea.js”}{/script}. Cambia las llaves por símbolos mayor que y menor que.

Saludos!

[ # 35544 ] Comment desde antuan [09 de Septiembre de 2008, 05:35]

En lugar de un botón donde pinchar para que salga el cuadro de búsqueda quiero que aparezca la caja de texto donde poner el criterio directamente, ¿alguien lo sabe?

saludos.

Escribe un Comentario





Estadísticas