Pregunta

Tengo problemas para llamar a una función de JavaScript en un iframe desde la página principal. Aquí están mis dos páginas:

mainPage.html

<html>
<head>
    <title>MainPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            if (document.all.resultFrame)
                alert("resultFrame found");
            else
                alert("resultFrame NOT found");

            if (typeof (document.all.resultFrame.Reset) == "function")
                document.all.resultFrame.Reset();
            else
                alert("resultFrame.Reset NOT found");
        }
    </script>
</head>
<body>
    MainPage<br>
    <input type="button" onclick="Reset()" value="Reset"><br><br>
    <iframe height="100" id="resultFrame" src="resultFrame.html"></iframe>
</body>
</html>

resultFrame.html

<html>
<head>
    <title>ResultPage</title>
    <script type="text/javascript">
        function Reset() 
        {
            alert("reset (in resultframe)");
        }
    </script>
</head>
<body>
    ResultPage
</body>
</html>

(Sé que document.all no se recomienda, pero esta página solo debe verse con IE internamente y no creo que ese sea el problema)

Cuando presiono el botón Restablecer, aparece " resultFrame found " y " resultFrame.Reset NO encontrado " ;. Parece tener una referencia al marco, pero no puede llamar a la función en el marco, ¿por qué?

¿Fue útil?

Solución

Uso:

document.getElementById("resultFrame").contentWindow.Reset();

para acceder a la función de reinicio en el iframe

document.getElementById (" resultFrame ") obtendrá el iframe en su código, y contentWindow obtendrá el objeto de ventana en el iframe. Una vez que tenga la ventana secundaria, puede consultar javascript en ese contexto.

Consulte también AQUÍ en particular la respuesta de bobince.

Otros consejos

En lugar de obtener el marco del documento, intente obtener el marco del objeto de la ventana.

en el ejemplo anterior cambie esto:

if (typeof (document.all.resultFrame.Reset) == "function")
    document.all.resultFrame.Reset();
else
    alert("resultFrame.Reset NOT found");

a

if (typeof (window.frames[0].Reset) == "function")
    window.frames[0].Reset();
else
    alert("resultFrame.Reset NOT found");

el problema es que el alcance del javascript dentro del iframe no está expuesto a través del elemento DOM para el iframe. solo los objetos de ventana contienen la información de alcance de javascript para los marcos.

Para mayor robustez:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

y

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.reset();
  ...
}
...

Llamar

window.frames['resultFrame'].Reset();

objectframe.contentWindow.Reset () necesita primero una referencia al elemento de nivel superior en el marco.

La primera y más importante condición que debe cumplirse es que tanto el padre como el iframe deben pertenecer al mismo origen. Una vez hecho esto, el niño puede invocar al padre usando el método window.opener y el padre puede hacer lo mismo para el niño como se mencionó anteriormente

Cuando accede a resultFrame a través de document.all solo lo extrae como un elemento HTML, no como un marco de ventana. Obtiene el mismo problema si tiene un marco disparar un evento usando un " this " auto-referencia.

Reemplazar:

document.all.resultFrame.Reset();

Con:

window.frames.resultFrame.Reset();

O:

document.all.resultFrame.contentWindow.Reset();

Si no puede usarlo directamente y si encuentra este error: Bloqueado un marco con origen " http: // www ..com " de acceder a un marco de origen cruzado. Puede usar postMessage () en lugar de usar el funcionar directamente.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top