Una técnica muy utilizada últimamente es la grabación con AJAX del texto seleccionado, lo que puede resultar muy útil para detectar qué términos de nuestra web comparten o copian y pegan en los buscadores nuestros visitantes.
En el artículo de hoy hemos duplicado esa funcionalidad utilizando una librería javascript MooTools y otra librería JavaScript jQuery. ¡Utiliza la que te resulte mejor!
MooTools
-
window.addEvent('domready',function(){
-
//gets the selected text
-
var getSelection = function() {
-
return $try(
-
function() { return window.getSelection(); },
-
function() { return document.getSelection(); },
-
function() {
-
var selection = document.selection && document.selection.createRange();
-
if(selection.text) { return selection.text; }
-
return false;
-
}
-
) || false;
-
};
-
//event to listen
-
var selectRequest = new Request({
-
url: 'ajax-selection-copy.php',
-
method: 'post'
-
});
-
$('content-area').addEvent('mouseup',function(e) {
-
var selection = getSelection();
-
if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
-
selectRequest.send('selection=' + encodeURI(selection));
-
}
-
});
-
});
El primer paso es intentar tomar el texto seleccionado durante el mouseup (es decir, durante el momento en que el mouse se posiciona sobre el texto) con nuestro contenedor designado. Si encontramos una selección de texto, disparamos una petición AJAX a un script PHP que guardará la selección del texto.
jQuery
-
/* attempt to find a text selection */
-
function getSelected() {
-
if(window.getSelection) { return window.getSelection(); }
-
else if(document.getSelection) { return document.getSelection(); }
-
else {
-
var selection = document.selection && document.selection.createRange();
-
if(selection.text) { return selection.text; }
-
return false;
-
}
-
return false;
-
}
-
/* create sniffer */
-
$(document).ready(function() {
-
$('#content-area').mouseup(function() {
-
var selection = getSelected();
-
if(selection && (selection = new String(selection).replace(/^\s+|\s+$/g,''))) {
-
$.ajax({
-
type: 'post',
-
url: 'ajax-selection-copy.php',
-
data: 'selection=' + encodeURI(selection)
-
});
-
}
-
});
-
});
El código MooTools, traducido a jQuery. Básicamente realiza las mismas acciones.
PHP
-
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && $selection = trim($_POST['selection'])) {
-
mysql_query('INSERT INTO text_selections (selection,date_selected) VALUES(\''.mysql_escape_string(stripslashes($selection)).'\',NOW())');
-
}
Este código PHP es muy primitivo. Dependiendo de la programación de tu sistema (seguridad, framework PHP, configuración, etc.) preferirás implementar algunas medidas adicionales para prevenir ataques en este script.
Haz clic aquí para ver la demostración en MooTools »
Haz clic aquí para ver la demostración en jQuery »
Grabar selecciones de texto es una gran forma de descubrir qué tópicos o términos interesan más a tu audiencia.
Fuente: David Walsh Blog








Comentarios recientes
- Adriana Suárez: PARA MÍ, EL MEJOR WINDOWS ES EL 98, LAS VERSIONES QUE SALIERON DESDE 20...
- RENZO LOPEZ GARCIA: Como ago para conseguir código para crear un registro que lleve esta de...
- RENZO LOPEZ GARCIA: creo que es bueno que in contremos paginas de orientacion deverdad bueno...
- Rony Xp: yo recominedo windows falcor lo instale en una p2 y anda como Dual core!...
- Profesor Yeow: Muy interesante! una consulta... se puede usar divs o todo tiene que ser...
- Rafael: La ley SOPA o el acuerdo ACTA buscan poner bajo control lo que hasta ah...
Feed de los comentarios