如何在iframe中调用父窗口JavaScript函数
这是我在如何在iframe中调用父窗口JavaScript函数,javascript,html,iframe,cross-domain,Javascript,Html,Iframe,Cross Domain,这是我在http://my-localhost.com/iframe-test.html <html> <head><title>Welcome Iframe Test</title></head> <body> <iframe src="http://www.my-website.com/index.html" width="500" height="500"></iframe> <scrip
http://my-localhost.com/iframe-test.html
<html>
<head><title>Welcome Iframe Test</title></head>
<body>
<iframe src="http://www.my-website.com/index.html" width="500" height="500"></iframe>
<script type="text/javascript">
function alertMyMessage(msg){
alert(msg);
}
</script>
</body>
</html>
<html>
<head></title>Welcome to my Server</title></head>
<body>
<h1>Welcome to My Server</ht>
<a href="javascript:void(0)" title="Click here" onClick="parent.alertMyMessage('Thanks for Helping me')">Click Here</a>
</body>
</html>
当我点击“点击这里”链接时。我犯了以下错误
未捕获的安全性错误:阻止了具有原点的帧
“”访问具有原点的帧
"". 协议、域和端口必须匹配
请帮助我解决此问题,或提供其他解决方案。您无法访问加载在不同来源的框架中的页面的DOM。这是出于安全原因而被阻止的(假设您访问的一个随机网站在一个隐藏的iframe中打开了web邮件服务,您可以看到原因) 只有在你控制了这两个网站的情况下,你才能做到的最接近的一点就是使用 在一个页面中,编写一个函数来处理消息,然后将其添加为消息事件侦听器
function receiveMessage(event)
{
alert(event.data);
}
addEventListener("message", receiveMessage, false);
在另一个窗口中,发送以下消息:
parent.postMessage("This is a message", "*");
请参见您可以使用postMessage 父母亲 IFRAME 参考文献
为什么要使用iFrame?那么我可以使用什么呢?实际上,我的目的是我有固定的html页面,这将打开许多网站。这些网站的用户必须点击一个链接,链接应该在固定的html页面中调用一个函数。Thank将尝试:)并让你知道Thank这个方法在Chrome上工作。但是在Safari中它不起作用:(@Quentin Neat.Using Chrome,我收到了消息,但它没有显示iframe窗口的位置。
Uncaught SecurityError:阻止了一个带有原点的帧”http://fiddle.jshell.net“从访问具有原点的帧”http://stone.thecoreworlds.net"。协议、域和端口必须匹配。
@Chloe-这是因为您必须使用postMessage
来传递数据,而尝试读取位置的代码却没有。使用##
作为标题。这很有效!但是有没有一种方法可以动态填充“”而不是硬代码?我可以使用location.anteStororigines[0])而不是硬编码的“我注意到窗口IE11在函数send()上抛出脚本70“权限被拒绝”。有办法解决这个问题吗?
if (window.addEventListener) {
window.addEventListener ("message", receive, false);
}
else {
if (window.attachEvent) {
window.attachEvent("onmessage",receive, false);
}
}
function receive(event){
var data = event.data;
if(typeof(window[data.func]) == "function"){
window[data.func].call(null, data.params[0]);
}
}
function alertMyMessage(msg){
alert(msg);
}
function send(){
window.parent.window.postMessage(
{'func':'alertMyMessage','params':['Thanks for Helping me']},
'http://www.my-website.com'
);
}