2014-05-08 2 views
3

J'ai deux iframes. Ces iframes communiquent ensemble via postMessage.Deux Iframes communiquent: SecurityError

D'un iframe, si je fais ce qui suit, cela ne fonctionne pas.

// Broadcast to all iframes. 
parent.frames.forEach(function (frame) { 
    frame.postMessage(data, 'http://localhost:4000'); 
}); 

Erreur:

Uncaught SecurityError: Blocked a frame with origin "http://..." from accessing a frame with origin "http://...". Protocols, domains, and ports must match.

Cependant, si je fais ce qui suit, il fonctionne très bien. Aucun message d'erreur Pourquoi?

for (var i = 0 ; i < parent.frames.length ; ++i) { 
    parent.frames[i].postMessage(data, 'http://localhost:4000'); 
} 
+2

Le question ici ressemble à ce que l'on peut lire comme "Pourquoi' parent.frames.forEach' donne un _SecurityError_ quand je peux itérer sur eux dans un 'for'?" –

Répondre

2

La question semble ici comme il peut être lu comme

Why does parent.frames.forEach give a SecurityError when I can iterate over them in a for ?

C'est parce que parent.frames est pas un tableau mais une fenêtre instance et par conséquent, lorsque vous essayez de accéder .forEach, il est à la recherche d'une propriété sur une autre fenêtre dont la sécurité empêche l'accès.

A partir de la page MDN de window.frames (parent est une fenêtre)

Returns the window itself, which is an array-like object, listing the direct sub-frames of the current window.

Si vous souhaitez utiliser .forEach, prenez de (a referencabe) prototype de tableau

Array.prototype.forEach.call(parent.frames, callback); 
Questions connexes