2012-12-26 60 views
1

我已经收到来自这个网站的JavaScript代码。使用javascript检索IFrame内容

alert(window.frames['sc_frame'].document.getElementsByTagName('body')[0].innerHTML); 

alert(window.frames['sc_frame'].document.getElementsByTagName('body')[0].innerText); 

的问题是我有这个错误。

Unsafe JavaScript attempt to access frame with URL http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx from frame with URL http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxx. Domains, protocols and ports must match. 
(anonymous function) 
InjectedScript._evaluateOn 
InjectedScript._evaluateAndWrap 
InjectedScript.evaluate 
TypeError: Cannot call method 'getElementsByTagName' of undefined 
arguments: Array[2] 
get message: function() { [native code] } 
get stack: function() { [native code] } 
set message: function() { [native code] } 
set stack: function() { [native code] } 
type: "non_object_property_call" 
__proto__: Error 

我也明白原因,因为我的IFrame正在呼叫另一个域。

<iframe id="sc_frame" src="http://example1.com"></iframe> 

我使用上面的代码从http://example.com

我的问题是是否有解决方法。要么使用JavaScript或任何其他方法?

回答

0

由于安全限制,您无法直接与域中的其他元素(/ ports/protocols)进行通信。您不仅无法访问目标文档源,也无法访问对象和事件。

可以做什么,是使用框架通过代理跨域发送消息。 This answer谈论这一点。

+0

那么,根据这个答案,我们需要在'example1.com'中写些东西来将信息传递回'example.com'?我真的明白这意味着什么.. Sry – william

+0

我在说的是两个来自不同域的iframe之间的通信,而不是服务器到服务器之间的通信(当然这也是可能的,但不是你要求的)。我所讨论的框架允许您将example1.com中的iframe发送给代理服务器(yourproxy.com),然后example.com中的iframe可以与yourproxy.com进行通信,并询问“我是否有来自example1.com iframe的任何消息?“。这样两个iframe可以进行通信,但不能直接在它们之间进行通信。 – TheZuck

+0

我明白了。得到它了。谢谢.. – william