Running Javascript in new window.open

Scripts added with .innerHTML aren’t executed. You need to create a script node and append it to the window’s DOM.

$("#button").click(newWindow);

function newWindow(id) {
  var html = $(id).html();
  var win = window.open('');
  win.document.head.innerHTML = '<title>Hi</title></head>';
  win.document.body.innerHTML = '<body>' + html + '</body>';
  var script = document.createElement('script');
  script.src="https://stackoverflow.com/questions/32357312/js/myScript.js";
  win.document.head.appendChild(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click me</button>

This doesn’t run in Stack Snippet’s sandbox, here’s a working jsfiddle.

Leave a Comment