Skip to content Skip to sidebar Skip to footer

Pass Value To Child Window Using Javascript

I'm attempting to get the question id from the parent page and pass it into my new child page. When the child window gets a response it will put this data into text_body id. I have

Solution 1:

Due to cross-domain restrictions, browsers have clamped down on the security of opening pop-ups and iframes.

The reason you are getting the Cannot set property 'value' of null is that you are trying to run the code to open a window directly from javascript - without any user action.

This will prevent the code running correctly, so the 'value' (property or variable) on null (k the child window) is your error; k is null at the time you are trying to set the variable 'value'.

Browsers will request permission to allow pop-ups in different ways. If the user hasn't clicked on something to request the pop-up, permission hasn't yet been given to allow it.

The sample code below demonstrates that you will get the error for the initial call to open the window and set the child's variable without user action, but when the user clicks on something (the div in this case), it will open after confirming permission.

Open the console window, refresh the page and you will see the error for the non-interactive call.

The working parts of the demo use an initial value to display in the child window, then after 1.5 seconds, the parent will call a function in the child that will update the display, and finally, the parent will access a child variable and set the display directly.

Timers are just for clarity to see the changes as they happen.

Hopefully this covers what you are trying to do...

parentPage.html:

<html><head><title>Parent Page</title></head><body><divid="divQuestion"onclick="openChild()">Parent text</div><script>functionopenChild() {
            var parentText = document.getElementById("divQuestion").innerText;
            var win = window.open("childPage.html");

            // Call a function in the child window...    setTimeout(function () { win.changeValue(parentText) }, 1500);

            // Directly use a variable in the child window...setTimeout(function () { win.childText.innerText = body + " and some more..." }, 3000);
        }

        // By calling directly you are attempting to open a child window // without user permission - this will fail.// openChild();</script></body></html>

childPage.html:

<html><head><title>Child Page</title></head><body><divid="divText">Child text</div><script>var childText = document.getElementById("divText");

        functionchangeValue(val) {
            // Take a value from elsewhere (parent window in this case) and update the div
            childText.innerText = val;
        }
    </script></body></html>

Post a Comment for "Pass Value To Child Window Using Javascript"