如何使用 JavaScript 访问跨域 iFrame 内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4912670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JavaScript to access cross domain iFrame content?
提问by monkey_boys
I would like to use this code
我想使用此代码
window.parent.document.getElementById('message').value += "\r\n\r\n[img]"+response+"[/img]";
It works fine for pages coming from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?
它适用于来自同一域的页面,但不适用于 iFrame 中加载的另一个域的站点。我该怎么做?
回答by Stefan Steiger
You can implement window.postMessage to communicate accross iframes/windows across domains.
您可以实现 window.postMessage 跨域跨 iframes/windows 进行通信。
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
// What browsers support the window.postMessage call now?
// IE8 does not allow postMessage across windows/tabs
// FF3+, IE8+, Chrome, Safari(5?), Opera10+
function SendMessage()
{
var win = document.getElementById("ifrmChild").contentWindow;
// http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/
// http://stackoverflow.com/questions/16072902/dom-exception-12-for-window-postmessage
// Specify origin. Should be a domain or a wildcard "*"
if (win == null || !window['postMessage'])
alert("oh crap");
else
win.postMessage("hello", "*");
//alert("lol");
}
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if (false) {
message = 'You ("' + evt.origin + '") are not worthy';
}
else {
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if (ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
//evt.source.postMessage("thanks, got it ;)", event.origin);
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
<br />
<input type="button" value="Test" onclick="SendMessage();" />
</body>
</html>
Child.htm
儿童.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
/*
// Opera 9 supports document.postMessage()
// document is wrong
window.addEventListener("message", function (e) {
//document.getElementById("test").textContent = ;
alert(
e.domain + " said: " + e.data
);
}, false);
*/
// https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
// http://ejohn.org/blog/cross-window-messaging/
// http://benalman.com/projects/jquery-postmessage-plugin/
// http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
// .data – A string holding the message passed from the other window.
// .domain (origin?) – The domain name of the window that sent the message.
// .uri – The full URI for the window that sent the message.
// .source – A reference to the window object of the window that sent the message.
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if(false)
{
message = 'You ("' + evt.origin + '") are not worthy';
}
else
{
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
//alert(evt.source.location.href)
var ta = document.getElementById("taRecvMessage");
if(ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
// http://javascript.info/tutorial/cross-window-messaging-with-postmessage
//evt.source.postMessage("thanks, got it", evt.origin);
evt.source.postMessage("thanks, got it", "*");
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body style="background-color: gray;">
<h1>Test</h1>
<textarea id="taRecvMessage" rows="20" cols="20" ></textarea>
</body>
</html>
回答by Sean Kinsey
Take a look at easyXDM, it's an easy to use library that provides a unified API for several tricks used to enable cross domain messaging, ranging from postMessage to the FIM-trick as a last resort.
This is what is used by major services such as Twitter and Disqus.
看看easyXDM,它是一个易于使用的库,它为用于启用跨域消息传递的几个技巧提供了统一的 API,范围从 postMessage 到作为最后手段的 FIM 技巧。
这是 Twitter 和 Disqus 等主要服务所使用的。
回答by Darin Dimitrov
Due to same origin policyrestrictions this is not allowed.
由于同源政策限制,这是不允许的。
回答by tw39124
You can't. This is called the same origin policy, and prevents javascript accessing content across domains.
你不能。这称为同源策略,可防止 javascript 跨域访问内容。
回答by leebriggs
As stated, this falls under same origin policy, but there are some tricks that allow limited communication with the iframe. Take a look at http://ajaxify.com/run/crossframe/
如前所述,这属于同源策略,但有一些技巧允许与 iframe 进行有限的通信。看看http://ajaxify.com/run/crossframe/
回答by setec
You can if your browser have disabled security, for chrome it's
如果您的浏览器禁用了安全性,则可以,对于 chrome,它是
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security
Update: I'm surprised that people keep devoting it because they consider it harmful, so here I add some additional details for peoples who don't know basics of web security and still try to develop for it.
更新:我很惊讶人们一直致力于它,因为他们认为它有害,所以在这里我为那些不了解 Web 安全基础知识但仍在尝试为其开发的人们添加一些额外的细节。
DON'T use this solution if
如果出现以下情况,请不要使用此解决方案
you are using chrome plugins or apps which are not trusted by you, or
you have opened other sites in the chrome, or
you have some malicious chrome processes
your site is using any external resources.
您正在使用不受您信任的 chrome 插件或应用程序,或者
您在 chrome 中打开了其他网站,或者
你有一些恶意的 chrome 进程
您的网站正在使用任何外部资源。
To make this solution completely safe, configure your firewall to block all connections except one to which you are making CORS connection.
为使此解决方案完全安全,请将防火墙配置为阻止所有连接,但要与之建立 CORS 连接的连接除外。
Also, don't use this solution if your connection endpoint isn't trusted.
此外,如果您的连接端点不受信任,请不要使用此解决方案。