I want to have cross domain javascript call.
1: SiteA: www.sub1.foo.com
2: Open SiteB: www.bar.com in iframe from SiteA
3: Pass some value from SiteB to SiteA via javascript after some action in SiteB.
Try 1:
I followed this article and I followed #2 for my setup. But I keep getting errors:
IE: Invalid Argument
FF:Illegal document.domain value.
Try 2:
Followed this article.
It works in FF. I can use window.parent.parent.MyFunction() but in IE I get "Permission Denied" error.
Try 3:
I even tried the window.postMessage technique but I am not even able to get that working.
Is anyone out there who has successfully implemented Cross Domain JS calls for situation like above.
Or any help / links / suggestions.
You can implement window.postMessage to communicate accross iframes/windows across domains.
<!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
<!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>
I believe this is restricted for security reasons.
It's been discussed previously on Stack Overflow here: <iframe> javascript access parent DOM across domains?
I did something like this: http://blog.johnmckerrell.com/2006/10/22/resizing-iframes-across-domains/
some time ago :)
Related
In IE on Windows 10 with default settings, if I perform a window.open() against an external internet site from a page on my local machine or a server on my local network, I get null.
See my repro below. This doesn't happen in IE on Windows 7 or Google Chrome.
Interestingly, if I turn on "Enable Protected Mode" for the Intranet Zone (so that Protected Mode are the same in the Intranet Zone and Internet Zone), then the problem goes away. However, I need this to work without requiring users to do this.
I haven't found any clear Microsoft documentation that explains this behavior. I raised an issue on this on the EdgeHTML issues site, but wanted to see if the community on SO has any insight into why this is happening.
Thanks!
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script>
var popupWindow = null;
function openWindow() {
popupWindow = window.open('http://microsoft.com', '_blank', 'left=100;top=100;height=100;width=100');
}
function checkWindowStatus() {
if (popupWindow) {
document.getElementById('status').innerHTML += '- Truthy reference. Closed? ' + popupWindow.closed + '</br>';
} else {
document.getElementById('status').innerHTML += '- Falsy reference: ' + popupWindow + '</br>';
}
}
</script>
</head>
<body>
<h2>Popup Issue</h2>
<button onclick="openWindow()">Open Window</button>
<button onclick="checkWindowStatus()">Check Window Status</button>
<button onclick="popupWindow.close()">Close Window</button>
<p id="status"></p>
</body>
</html>
It seems that protected mode doesn't allow to open new window outside of the current domain, so you can try to open the window with a blank page and after update the location.
<script>
var popupWindow = null;
function openWindow() {
popupWindow = window.open('', '_blank', 'left=100;top=100;height=100;width=100');
popupWindow.location = 'http://microsoft.com';
}
function checkWindowStatus() {
if (popupWindow) {
document.getElementById('status').innerHTML += '- Truthy reference. Closed? ' + popupWindow.closed + '</br>';
} else {
document.getElementById('status').innerHTML += '- Falsy reference: ' + popupWindow + '</br>';
}
}
</script>
I need to access the Parent Domain URL from my Iframe which is in another domain.
For example, "example.com" is my website which has an Iframe from another parent domain, such as "google.com". Here I need to access the parent domain URL from my example.com. That is, I need to get the URL "google.com" in my "example.com" domain. Moreover, the Parent domain cannot be hard coded.
What I tried was using the following code:
window.parent.location.href()
but this results in Access denied error. How do I implement this properly in order to achieve this?
You can try and check for the referer, which should be the parent site if you're an iframe
you can do that like this:
var href = document.referrer;
You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :
cross domain access in iframe from child to parent
<iframe> javascript access parent DOM across domains?
How to access parent Iframe from javascript
To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.
The Same origin policy page on wikipedia brings some informations about that security measure :
In a nutshell, the policy permits
scripts running on pages originating
from the same site to access each
other's methods and properties with no
specific restrictions — but prevents
access to most methods and properties
across pages on different sites.
A strict separation between content
provided by unrelated sites must be
maintained on client side to prevent
the loss of data confidentiality or
integrity.
Instead of using the referrer, you can implement window.postMessage to communicate accross iframes/windows across domains.
You post to window.parent, and then parent returns the URL.
This works, but it requires asynchronous communication.
You will have to write a synchronous wrapper around the asynchronous methods, if you need it synchronous.
<!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
<!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>
You have a couple of options:
Scope the domain down (see document.domain) in both the containing page and the iframe to the same thing. Then they will not be bound by 'same origin' constraints.
Use postMessage which is supported by all HTML5 browsers for cross-domain communication.
Good article here:
Cross-domain communication with iframes
Also you can directly set document.domain the same in both frames (even
document.domain = document.domain;
code has sense because resets port to null), but this trick is not general-purpose.
try
window.frameElement.ownerDocument.domain
On Load of Access.aspx a javascript function is called.
<head>
<title>access</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<link href="rtsBanner.css" type="text/css" rel="stylesheet">
<script language="JavaScript" type="text/javascript" src="winopen.js"> </script>
<script type="text/javascript" language="javascript">
function openLogin(site, pass) {
var loginUrl = 'login.aspx';
if (site != '' && pass != '') {
loginUrl += '?SITE=' + site + '&PASS=' + pass;
}
else if (site != '') {
loginUrl += '?SITE=' + site;
}
var popUpFeatures = 'dialogHeight: 385px; dialogWidth: 600px; edge: Raised; center: Yes; help: No; resizable: No; scroll: Yes; status: No;';
var RetVal = window.showModalDialog(loginUrl, 'null', popUpFeatures);
if (typeof (RetVal) == 'undefined') {
top.window.close();
}
else {
var RetArray = RetVal.split(',')
var ValidLogon = RetArray[0];
var MUName = RetArray[1];
if (ValidLogon == 1) {
document.location.href = 'newRequest.aspx?desc=' + MUName;
}
else {
top.window.close();
}
} // else(typeof(RetVal)
}
</script>
</head>
<body ms_positioning="GridLayout" onload="openLogin('<%=Request("SITE")%>','<%=Request("PASS")%>');">
<form id="Form1" method="post" runat="server">
</form>
</body>
</html>
This code works perfectly in IE but in safari on the login screen after I enter site name and password and hit login button it doesn't redirect me to the newRequest.aspx page instead just closes the login popup and shows a blank access.aspx page.
Editted:
This is the code on btnLogin_Click on Login.aspx.vb page
If txtSiteName.Text = "" And txtPassPhrase.Text = "" Then Return
If ValidateSiteAndPass(txtSiteName.Text, txtPassPhrase.Text) = False Then
Throw New Exception("OOPS!!! Either SiteName or Pass Phrase is Invalid, please check")
Else
Session("valid") = "true"
Response.Write("<script language='javascript'>{window.returnValue='1," + txtSiteName.Text + "'; self.close();}</script>") '''document.Form1.submit();")
Response.End()
End If
Please suggest
Thanks,
Kavita
I found the solution here.
http://forums.asp.net/t/1400811.aspx/1
The problem was due to window.showModalDialog. It doesn't work properly in Safari.. I replaced it with window.open
Thanks,
Kavita
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?
You can implement window.postMessage to communicate accross iframes/windows across domains.
<!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
<!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>
You can if your browser have disabled security, for chrome it's
"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.
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.
To make this solution completely safe, configure your firewall to block all connections except one to which you are making CORS connection.
Also, don't use this solution if your connection endpoint isn't trusted.
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.
Due to same origin policy restrictions this is not allowed.
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/
You can't. This is called the same origin policy, and prevents javascript accessing content across domains.
I need to access the Parent Domain URL from my Iframe which is in another domain.
For example, "example.com" is my website which has an Iframe from another parent domain, such as "google.com". Here I need to access the parent domain URL from my example.com. That is, I need to get the URL "google.com" in my "example.com" domain. Moreover, the Parent domain cannot be hard coded.
What I tried was using the following code:
window.parent.location.href()
but this results in Access denied error. How do I implement this properly in order to achieve this?
You can try and check for the referer, which should be the parent site if you're an iframe
you can do that like this:
var href = document.referrer;
You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :
cross domain access in iframe from child to parent
<iframe> javascript access parent DOM across domains?
How to access parent Iframe from javascript
To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.
The Same origin policy page on wikipedia brings some informations about that security measure :
In a nutshell, the policy permits
scripts running on pages originating
from the same site to access each
other's methods and properties with no
specific restrictions — but prevents
access to most methods and properties
across pages on different sites.
A strict separation between content
provided by unrelated sites must be
maintained on client side to prevent
the loss of data confidentiality or
integrity.
Instead of using the referrer, you can implement window.postMessage to communicate accross iframes/windows across domains.
You post to window.parent, and then parent returns the URL.
This works, but it requires asynchronous communication.
You will have to write a synchronous wrapper around the asynchronous methods, if you need it synchronous.
<!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
<!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>
You have a couple of options:
Scope the domain down (see document.domain) in both the containing page and the iframe to the same thing. Then they will not be bound by 'same origin' constraints.
Use postMessage which is supported by all HTML5 browsers for cross-domain communication.
Good article here:
Cross-domain communication with iframes
Also you can directly set document.domain the same in both frames (even
document.domain = document.domain;
code has sense because resets port to null), but this trick is not general-purpose.
try
window.frameElement.ownerDocument.domain