Parent and child window connection with JS

Viewed 36

So I am new to Javascript and right now I am trying to make it so a child window/tab created from a parent page can affect said parent page.

I made a parent page with a button that opens a child page and on that child page upon choosing an option input and pressing a button the value should also appear on the parent page, but they don't and I am not sure why.

Here is the Parent page

<html>
<head>
</head>
<body>
<table cellpadding="0" cellspacing="0">
    <tr>
        <td>
            Name:&nbsp;
        </td>
        <td>
            <input type="text" id="txtName" readonly="readonly" />
        </td>
        <td>
            <input type="button" value="Select Name" onclick="SelectName()" />
        </td>
    </tr>
</table>
<script type="text/javascript">
    var popup;
    function SelectName() {
        popup = window.open("popup.html", "width=300,height=100");
        popup.focus();
        return false
    }
</script>
</body>
</html>

And here is the Child page

<html>
<head>
</head>
<body>
<select name="ddlNames" id="ddlNames">
    <option value="Name1">Name1</option>
    <option value="Name2">Name2</option>
    <option value="Name3">Name3</option>
</select>
<input type="button" value="Select" onclick="SetName();" />
<script type="text/javascript">
    function SetName() {
        if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");
            txtName.value = document.getElementById("ddlNames").value;
        }
        window.close();
    }
</script>
</body>
</html>

I am confused as to why the selected values from Child page don't appear in the Parent page.

1 Answers

What you are trying to achieve is blocked by this error:

DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

You'll need to serve the files by setting up a simple server, and then opening parent.html.

You can solve this by:

  • Installing node.js and npm
  • Running npm install -g http-server in your terminal.
  • Running http-server command in the folder where your html files are located

When you open the hosted files, the popup file should now be able to access and modify the parent file that called it.

Hope this helps.

Related