Reputation: 691
I have a javascript code which is connected to a htlm called "old.html". I do thing in there and then I have another html called "new.html" in which I want to add html elements in there.
I have this code in which I try to assign the div
q1 to the variable
myVar.
var printWindow = window.open("http://10.180.101.58:5500/new.html", 'Print');
var myVar = printWindow.document.getElementById('q1');
my html looks like this:
<body>
<form>
<div id="q1"></div>
</form>
<script src="DemoCode.js"></script>
</body>
These 2 files are in the same directory, but I think the problem is with the window.open()
I can't do document.getElementById()
because I also have the "old.html" which let's say is the original html connected to my javascript and whenever I call document.getElementById()
it gets elements from that one.
Does anyone know any way so that I can get elements from "new.html""?
I am using <script src="DemoCode.js"></script>
in both html's so I can say that both are connected to my javaScript.
Upvotes: 3
Views: 133
Reputation: 1074365
There are two answers here:
If the window where the code doing this is on the same origin (http://10.180.101.58:5500
),
you have to wait for the DOM to be loaded in the new window (for instance, using the DOMContentLoaded
event) before you can access it.
If the window where the code doing this isn't on the same origin as the new window you're opening, then you can't access its DOM, since of course that would be a massive security hole.
Here's how you'd do it in case #1:
const printWindow = window.open("http://10.180.101.58:5500/new.html", "Print");
printWindow.addEventListener("DOMContentLoaded", () => {
const myVar = printWindow.document.getElementById("q1");
// ...use it here...
});
I am using
<script src="DemoCode.js"></script>
in both html's so I can say that both are connected to my javaScript.
That doesn't in any way connect the windows (imagine all the windows that would be connected by jQuery or React loaded from a CDN!). All it does is load the code in that file into both windows.
Upvotes: 2