2009-09-24 31 views
17
<html> 
<body> 
    <script type="text/javascript"> 

    function smth() { 

    if (document.getSelection) { 
    var str = document.getSelection(); 
    if (window.RegExp) { 
     var regstr = unescape("%20%20%20%20%20"); 
     var regexp = new RegExp(regstr, "g"); 
     str = str.replace(regexp, ""); 
    } 
    } else if (document.selection && document.selection.createRange) { 
    var range = document.selection.createRange(); 
    var str = range.text; 
    } 

    alert(str); 
    } 
    </script> 

    <iframe id="my" width="300" height="225"> 
    .....some html .... 
    </iframe>  

    <a href="#" onclick="smth();">AA</a> 
</body>  
</html> 

con la función smth puedo obtener el texto seleccionado de algún div, pero no funciona con iframe. alguna idea de cómo obtener el texto seleccionado de iframe?cómo obtener el texto seleccionado de iframe con javascript?

Respuesta

6

No puede acceder a los datos dentro de un iframe que es de un dominio diferente al suyo. Esto se debe a Same origin policy.

+2

ejemplo ok, lo siento mal, en el marco flotante tengo texto, yo uso iframe para editor WYSIWYG, por lo que no es de dominio diferente. –

+0

Gracias por la información. –

6

Debe obtener la selección del documento/ventana en el iframe.

function getIframeSelectionText(iframe) { 
    var win = iframe.contentWindow; 
    var doc = win.document; 

    if (win.getSelection) { 
    return win.getSelection().toString(); 
    } else if (doc.selection && doc.selection.createRange) { 
    return doc.selection.createRange().text; 
    } 
} 

var iframe = document.getElementById("my"); 
alert(getIframeSelectionText(iframe)); 
17

document.getSelection

está en el documento externa. Para obtener la selección del documento en el iframe que necesita para agarrar el documento interno:

var iframe= document.getElementById('my'); 
var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility 

idoc.getSelection() 

Nota sin embargo, que WebKit no soporta document.getSelection() o document.selection. Intente reemplazarlo con window.getSelection() que funciona en Firefox y WebKit, pero devuelve un objeto de selección (una colección/envoltura alrededor de Rangos), que necesita encadenar:

var idoc= iframe.contentDocument || iframe.contentWindow.document; 
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView; 

''+iwin.getSelection() 

No estoy seguro de cuál es el punto de esto es:

if (window.RegExp) { 
    var regstr = unescape("%20%20%20%20%20"); 
    var regexp = new RegExp(regstr, "g"); 
    str = str.replace(regexp, ""); 
} 

RegExp es JavaScript básica se remonta a la versión más temprana; siempre estará ahí, no tienes que olfatearlo. La codificación URL de múltiples espacios es bastante innecesaria. Ni siquiera necesita RegExp como tal, un reemplazo de cadena podría escribirse como:

str= str.split('  ').join(''); 
+0

window.getSelection() devuelve un objeto de selección, no un rango. toString en la selección le dará el texto de selección. –

+0

Sí, ''' +' es un modismo para toString. – bobince

+0

Sí, lo sé. Estaba corrigiendo un error menor en su referencia al objeto de selección devuelto desde window.getSelection() como un Rango, pero estoy de acuerdo con usted en que su código funcionaría. –

2

El siguiente código devolverá el texto seleccionado.

function getSelectedText(frameId) { 
    // In ExtJS use: 
    // var frame = Ext.getDom(frameId); 
    var frame = document.getElementById(frameId); 

    var frameWindow = frame && frame.contentWindow; 
    var frameDocument = frameWindow && frameWindow.document; 

    if (frameDocument) { 
     if (frameDocument.getSelection) { 
      // Most browsers 
      return String(frameDocument.getSelection()); 
     } 
     else if (frameDocument.selection) { 
      // Internet Explorer 8 and below 
      return frameDocument.selection.createRange().text; 
     } 
     else if (frameWindow.getSelection) { 
      // Safari 3 
      return String(frameWindow.getSelection()); 
     } 
    } 

    /* Fall-through. This could happen if this function is called 
     on a frame that doesn't exist or that isn't ready yet. */ 
    return ''; 
} 

Espero que esto ayude a alguien.

+0

En firefox en la consola: Error: Permiso denegado para acceder al 'documento' de la propiedad. Está en la línea donde está: "var frameDocument = [... ] ". – Piotrek

1

Este código funciona en todos los navegadores modernos:

var iframe = document.getElementById('my'); 
var idoc = iframe.contentDocument || iframe.contentWindow.document; // ie compatibility 
var text = idoc.getSelection().toString(); 
Cuestiones relacionadas