1 September 2015

How to set text from iframe to parent using javascript

Hi All,

In this post I am going to show you how you can set the text on parent page by just clicking inside iframe.

So please use the below code for this purpose:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<script>
var isOverIFrame = false;
function processMouseOut() {
    isOverIFrame = false;
   
}
function processMouseOver() { isOverIFrame = true; }
function processIFrameClick() {
    if(isOverIFrame) {
 var newP = document.createElement("p");
      var text = document.createTextNode("Kunal Kumar");
      newP.appendChild(text);
      document.body.appendChild(newP);
      top.focus();
    }
}

function init() {
    var element = document.getElementsByTagName("iframe");
    for (var i=0; i<element.length; i++) {
        element[i].onmouseover = processMouseOver;
        element[i].onmouseout = processMouseOut;
    }
    if (typeof window.attachEvent != 'undefined') {
        top.attachEvent('onblur', processIFrameClick);
    }
    else if (typeof window.addEventListener != 'undefined') {
        top.addEventListener('blur', processIFrameClick, false);
    }
}
</script>
<iframe src="test.html">
</iframe>
<script>init();</script>
</body>
</html>



Once you run the page and click inside iframe you can see the text below iframe as many time you have clicked inside iframe as shown below:













Happy Coding :)


0 on: "How to set text from iframe to parent using javascript"