Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the innerHTML of some element in a window opened by a JavaScript window object?

I have some simple JavaScript code like this:

<script type="text/javascript">
   function openWindow() {
     var mywindow = window.open("file.html");
     mywindow.document.getElementById("foo").innerHTML="Hey you!!";
   }
</script>

This function is called with an onclick event. The window opens fine, but the element's innerHTML does not change. It is a file I own, so I know I am not being blocked by any security policy, and the element with id 'foo' definitely exists. (It is a DIV). I have tried other variations of .innerHTML like .src and .value, but nothing seems to work. Does anyone have any suggestions?

like image 287
RPIBuckHunter Avatar asked Oct 24 '25 18:10

RPIBuckHunter


2 Answers

The problem here is that you are most likely trying to access the DOM of the new window before that window has a chance to finish loading.

Consider the following:

<script type="text/javascript">
   function openWindow() {
     var mywindow = window.open("file.html");

     // register an onload event with the popup window so that we attempt to 
      // modify it's DOM only after it's onload event fires.
     mywindow.onload = function() {
         mywindow.document.getElementById("foo").innerHTML="Hey you!!";
     }

   }
</script>
like image 56
jmort253 Avatar answered Oct 27 '25 09:10

jmort253


Just of note... Even after fixing the timing of it you can also have errors with this if you are developing on your local machine instead of on the internet or a local server. I just wasted an hour trying to figure out why it wouldn't work, then uploaded the same code to my server and it worked fine. I was using code that I ran locally 2 years ago but in a different browser, changed a few lines and the browser and it stopped working until running on a server. Hope this helps someone.

like image 25
codesurgeon Avatar answered Oct 27 '25 07:10

codesurgeon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!