Click here to Skip to main content
15,886,857 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am opening a new window using javascript and write content to the new window. Part of the content is a javascript file, but the javascript does not execute in the new window. Help?

open.html:
XML
<script>
function winopen()
{
  var ghtml = "<h1>sasaasas</h1>";
  var gwin = window.open("", "_blank", "location=no,width=1000,height=600");
  if (gwin)
  { gwin.document.open();
    gwin.document.write(ghtml);

    var oscript = gwin.document.createElement("script");
    oscript.type = "text/javascript";
    oscript.src = "open.js";
    gwin.document.getElementsByTagName("head")[0].appendChild(oscript);

    //gwin.document.close();
  }
}
winopen();
</script>


open.js:
C#
function init() { alert("winwin"); }
setTimeout(function() { init(); }, 2000);
Posted

1 solution

In your code, you did not show anything which should trigger execution of your script. The solution is simple: you should have some script placed as a child of the element "body" or your "html" element. Another approach is adding the attribute onload to the <body> element (see, for example https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body[^]). As you did not show your HTML content of your created window, I am not sure if you tried to do so, most likely not.

—SA
 
Share this answer
 
Comments
Member 10292007 7-Jul-14 18:09pm    
Hi Sergey

Thanks for the reply and for taking so long to reply.
I managed to solve it in simple HTML, but the weird thing is that some parts work in IE and other work in chrome:

open.html
<body>
<input type="text" önclick="alert('text'); winopen();"></input>

<script>
function winopen()
{
var ghtml = "

sasaasas

";
var gwin = window.open("", "_blank", "location=no,width=1000,height=600");
if (gwin)
{ gwin.document.open();
gwin.document.write(ghtml);

var oscript = gwin.document.createElement("script");
oscript.type = "text/javascript";
oscript.src = "open.js";
//oscript.onload = function() { init(); };
gwin.document.getElementsByTagName("head")[0].appendChild(oscript);

//gwin.document.close();
}
}
winopen(); // works in IE11, not chrome
</script>
</body>


open.js
function init() { alert("winwin"); }
setTimeout(function() { init(); }, 2000); // work in chrome, not IE11

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900