securityerror property permission origin inside cross create contentwindow content javascript iframe selected

property - cómo obtener el texto seleccionado de iframe con javascript?



javascript iframe content (5)

<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 texto seleccionado de algún div, pero no funciona con iframe. ¿Alguna idea de cómo obtener el texto seleccionado de iframe?


document.getSelection

Está en el documento externo. Para obtener la selección del documento en el iframe, necesita tomar el documento interno:

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

Sin embargo, tenga en cuenta que WebKit no es compatible con document.getSelection() o document.selection . Intente reemplazarlo con window.getSelection() que funciona tanto en Firefox como en WebKit, pero devuelve un objeto de selección (una colección / envoltura alrededor de Rangos), que necesita enhebrar:

var idoc= iframe.contentDocument || iframe.contentWindow.document; var iwin= iframe.contentWindow || iframe.contentDocument.defaultView; ''''+iwin.getSelection()

No estoy seguro de qué sentido tiene esto:

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

RegExp es un JavaScript básico que data de la versión más antigua; 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('''');


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));


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.


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();


No puede acceder a los datos dentro de un iframe que proviene de un dominio diferente al suyo. Esto se debe a la misma política de origen .