allow javascript iframe redirect

javascript - allow iframe



Usando JS, ¿cómo puedo evitar que los Iframes secundarios se redireccionen o, al menos, preguntar a los usuarios sobre la redirección? (3)

Puedes intentar crear frame buster buster, todo lo describe Jeff Atwood en su blog: We Done Been ... Framed! - coddinghorror.com

En resumen, debes implementar algo como esto:

var prevent_bust = 0 window.onbeforeunload = function() { prevent_bust++ } setInterval(function() { if (prevent_bust > 0) { prevent_bust -= 2 window.top.location = ''http://server-which-responds-with-204.com'' // replace your iframe with link to it } }, 1)

Muchos sitios tienen scripts similares al siguiente. Estos se ponen para evitar que otras personas puedan enmarcar los sitios.

if (top.location != location) { top.location.href = document.location.href; }

Necesito alguna forma de darme cuenta de que el iframe está intentando redirigir, y si lo es, eliminaré el iFrame y en su lugar colocaré un enlace al sitio. De esta forma, no violo la política de uso del sitio web enmarcado y también el enlace al sitio. Entiendo que puede usar el evento onbeforeunload como se discutió aquí y aquí, pero ambos parecen realmente no éticos. Recuerdo haber leído en alguna parte sobre una biblioteca que hace exactamente lo mismo (digg hace lo mismo). ¿Alguna pista?


El problema con la solución anterior es que se puede eliminar usando un simple:

if( top != self ) delete top.onbeforeunload;

Una vez que ha sido llamado, entonces prevent_bust nunca se incrementará, y eso significa que el sitio web será redirigido libremente sin su consentimiento o conocimiento. Mal trato.

Si querías una versión consistentemente funcional de esa solución, te recomendaría hacer esto en su lugar:

// Create a random seed value, making it almost impossible to // determine what is being tested for. var prevent_bust = Math.random() * 3000; // enclose everything in a function, so that it cannot be addressed function iniFunc ( init ) { // The function is no longer in scope of the main window. function onbeforeunload() { prevent_bust++ } window.onbeforeunload = onbeforeunload; setInterval( function() { // make sure the function was not deleted. if( window.onbeforeunload != onbeforeunload ) { prevent_bust = init + 1; window.onbeforeunload = onbeforeunload; } if (prevent_bust > init ) { // All comparison is to the random seed. prevent_bust -= 2 window.top.location = ''http://server-which-responds-with-204.com/'' // Unfortunately, you have absolutely no idea which website caused // the incrementation, so you cannot replace it with a link! // // You might try to simply ignore it and just use the iframe as is -- // theoretically, they are no longer able to bust this frame. // (this theory will be disproved below). } }, 1 ); }; iniFunc( prevent_bust );

Desafortunadamente, esto deja un problema: es trivial recuperar el intervalo que se ha establecido, deshacerlo y luego redirigir la página:

// setTimeout will return the highest timeout which is not "in use", in this case, // it will be the original setInterval (from the above function) + 1. // Event if there are 1,000 intervals already set, it will be rather trivial to // clear them all. var currentInterval = 10000; // window.setTimeout( gotoHREF, 100 ); // clearInterval will not interfere with setTimeout, so we can clear all // of the Intervals already set. for( var i = 0; i < currentInterval; i++ ) top.clearInterval( i ); function gotoHREF(){ top.location.href = "http://<my-url/>"; }

Su mejor opción es en realidad resolver este problema del lado del servidor (si puede). Si tiene acceso al servidor para el sitio web que mantendrá los iframes, cree una ubicación intermedia provisional donde extraiga los datos del sitio web y luego quite las etiquetas del script:

// In php $dd = new DOMDocument(); // file_get_contents will simply convert the entire web address into a String $dd->loadXML( file_get_contents( "http://" . $_GET[ ''loadedURL'' ] ) ); $scripts = $dd->getElementsByTagName( "script" ); // iterate through the website and remove all script tags. for( $i = 0; $i < $scripts->length; $i++ ) { $current = $scripts->item( $i ); $current->parentNode->removeChild( $current ); } // output it to the dummy page. echo $dd->saveXML();

Luego usarías la etiqueta:

<iframe src="redirect.php?loadedURL=http://www.google.com"></iframe>

Desafortunadamente, esto significará que su iframe se ejecutará sin JavaScript, lo que podría paralizar, si no lobotomize completamente el sitio web en cuestión. También deberá asegurarse de que todos los atributos src se hayan modificado correctamente para los nodos descendientes en el HTML del sitio externo.

Por otro lado, podría hacer que su servidor verifique el sitio enmarcado y todas sus páginas JS para ver si la ubicación superior de RegExp (. | [/ S * ("| '')) (esto coincidirá con top.location, top [ "ubicación, y top [''ubicación''] existe (o si hay alguna referencia a top) y luego use un enlace si existe y el sitio apropiado si no existe. El detrimento aquí es que entonces está forzando al usuario a esperar que el sitio secundario cargue dos veces, una vez en el servidor y otra en su navegador. (a menos que todo se haga a través de JS, pero eso es generalmente más molesto, en mi opinión).

Personalmente, soy de la opinión de que la multitud de "no enmarcar mi sitio" generalmente puede ganar la mayoría de las batallas, lo que implica directamente al iframe. Por otro lado, si el código se utiliza para procesar el HTML antes de que se anexe a una página web, entonces el otro lado es más que una posibilidad de lucha.



Como nota al margen, todo esto se puede lograr a través de JavaScript y AJAX, pero en general será un poco más lento. Usa el servidor, si puedes.


Si está utilizando HTML5, le sugiero que haga uso de la nueva propiedad "sandbox" PERO aún no es compatible con todos los navegadores. http://www.w3schools.com/tags/att_iframe_sandbox.asp

En mi caso, acabo de agregar "allow-forms" y "allow-scripts" como los valores de las propiedades de la zona de pruebas y el sitio incrustado ya no se redirecciona y aún se puede ejecutar JavaScript

¡usar "allow-top-navigation" como valor hizo que el sitio redirigiera nuevamente!

ex: <iframe sandbox="allow-forms allow-scripts" ... /></iframe>

Si alguien sabe algún inconveniente para usar este enfoque, me encantaría saberlo.

Alguien más con la misma respuesta: https://.com/a/9880360/1404129 (me encontré con esta respuesta más adelante)