跨子域 iframe 和 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6046558/
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
Cross sub domain iframes and JavaScript
提问by RyanP13
I am working on a CMS site whose domain is:
我正在一个 CMS 站点上工作,其域是:
http://www.acmssite.com
They have a sub-domain where they store a form system:
他们有一个子域,用于存储表单系统:
http://www.forms.acmssite.com
I have an iframe on the first that looks at a form in the latter.
我在第一个上有一个 iframe,它查看后者中的一个表单。
I need to run scripts to manipulate the latter from the former and was wondering is this possible?
我需要运行脚本来从前者操作后者,并且想知道这可能吗?
回答by Dark Falcon
In order for this to not be restricted by the same origin policy, you will probably need to do this in both the pages:
为了使其不受同一源策略的限制,您可能需要在两个页面中执行此操作:
document.domain = "acmssite.com";
回答by Cobra_Fast
Yes it is.
是的。
var iframe = document.getElementById("your-iframes-id").contentWindow.document;
回答by Gihan Gamage
You can still bypass this issue with the help of YQL even though you don't have access to the header part of the receiving window. With the Postmessage method also you need to edit the recipient window script. But using this method you can load any iframe without touching their scripts. Check this out! jsfiddle-link
即使您无权访问接收窗口的标题部分,您仍然可以在 YQL 的帮助下绕过此问题。使用 Postmessage 方法,您还需要编辑收件人窗口脚本。但是使用这种方法您可以加载任何 iframe 而无需触及它们的脚本。看一下这个!jsfiddle-link
<html>
<iframe src="https://google.com/" width="500" height="300"></iframe>
<script>
var iframe = document.getElementsByTagName('iframe')[0];
var url = iframe.src;
var getData = function (data) {
if (data && data.query && data.query.results && data.query.results.resources && data.query.results.resources.content && data.query.results.resources.status == 200) loadHTML(data.query.results.resources.content);
else if (data && data.error && data.error.description) loadHTML(data.error.description);
else loadHTML('Error: Cannot load ' + url);
};
var loadURL = function (src) {
url = src;
var script = document.createElement('script');
script.src = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=getData';
document.body.appendChild(script);
};
var loadHTML = function (html) {
iframe.src = 'about:blank';
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html.replace(/<head>/i, '<head><base href="' + url + '"><scr' + 'ipt>document.addEventListener("click", function(e) { if(e.target && e.target.nodeName == "A") { e.preventDefault(); parent.loadURL(e.target.href); } });</scr' + 'ipt>'));
iframe.contentWindow.document.close();
}
loadURL(iframe.src);
</script>
</html>