please anybody help me to set a cookie on parent window from a iframe in javascript. if it is possible, please provide some links related. ex:parent page has domain ABC
IFRAME on that page pointing to XYZ, i want to write a script in iframe to drop a cookie on ABC, that is on parent page.
please anybody help me to set a cookie on parent window from a iframe in javascript. if it is possible, please provide some links related. ex:parent page has domain ABC.
IFRAME on that page pointing to XYZ., i want to write a script in iframe to drop a cookie on ABC., that is on parent page.
Share Improve this question asked Oct 8, 2013 at 12:17 OnlineOnline 531 silver badge4 bronze badges 1- You can not set cookies for different domains. If you want to cookie set for abc., then abc. itself has to set it. – C3roe Commented Oct 8, 2013 at 12:28
2 Answers
Reset to default 3You can use postMessage to post from child window(i.e iFrame) and then listen the event at parent.
window.parent.postMessage("Value", "*");
window.addEventListener();
This post might help you to understand more. How do you use window.postMessage across domains?
Here is how you do it.
iFrame Website
Paste the below code in the iFrame website:
<script>
/* Sends a hello from the iframe to the parent */
parent.postMessage('hello_from_the_iframe', 'https://parentwebsite./');
</script>
Parent website
Paste the below code in the parent website where the iFrame is embedded to set cookie:
<script>
window.addEventListener("message",function (e) {
/*Check if the iframe website is sending the message*/
if(e.origin === 'https://iframewebsite.'){
/*Check if you got a hello from the iframe*/
if(e.data === 'hello_from_the_iframe'){
/*Function to set Cookie*/
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
/* Set the cookie 'set_my_cookie'*/
setCookie('set_my_cookie',1,365);
/* Get notification that the cookie is set*/
alert('cookie set');
}
}
},false);
</script>
You need to replace https://parentwebsite./
with the domain of the website where the iframe is embedded.
You also need to replace the https://iframewebsite.
with the origin of the iFrame. If you don't know the origin of the iFrame then just paste the below code in the iFrame HTML and it will be shown to you the origin in an alert box.
<script>
alert(window.location.origin);
</script>
Hope this helps.