0

I am trying to click on a button, and call the function to make it open a new window that is already exist using window.open() method, and at the same time, I want to change the new window's content using document.getElementById('para').innerHTML="New"; but I am not able to access and change the content.

<!DOCTYPE html>
<html>
<body>

<p>I want to click on the button and opens a new window, can change the new window's text "old"to the word "New", but I can't access the new window</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myWindow = window.open("newWindow.html", "MsgWindow", "width=200, height=100");
    myWindow.document.getElementById('para').innerHTML="New";
}
</script>

</body>
</html>

Below, it is the new window I am trying to access and manipulate

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

</head>

<body>

<p id="para">Old</p>
</body>
</html>

Thank you very much!

Hui

Hui Hao
  • 3
  • 1

2 Answers2

1

You have to wait for the new window to load its content. The content won't yet be available immediately after you open the window. You can use the window load event to know when it has finished loading and you can THEN modify its DOM when that event fires.

<script>
function myFunction() {
    var myWindow = window.open("newWindow.html", "MsgWindow", "width=200, height=100");
    myWindow.addEventListener("load", function() {
        myWindow.document.getElementById('para').innerHTML="New";
    });
}
</script>
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • However it did not work. Now when I click on the button, I don't see the new window anymore. – Hui Hao Oct 24 '14 at 03:51
  • @HuiHao - simple typo in my code. Fixed now. You should be able to look in the browser debug console and see simple syntax errors there yourself. That's the most basic debugging technique for Javascript. It's like coding in the dark if you can't see your basic typing errors. – jfriend00 Oct 24 '14 at 04:13
  • I noticed before with the closing ")" and ";" and I corrected them. Now the console doesn't complain anymore, there is no syntax error anymore. But new information still did not display in the new window. It still shows the "old" text. – Hui Hao Oct 24 '14 at 04:43
0

You must use sessionStorage to be able to change/pass information from one page to another before open new HTML page.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – Tyler2P Nov 13 '21 at 08:56