Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Javascript in new window.open

I'm running this function to open a new window.

function htmlNewWindow(id) {
    var html = $(id).html();
    var newWindow = window.open('');
    newWindow.document.body.innerHTML =  '<html><head><title>Hi</title>  <script src="js/myScript.js"></script> </head>' + html;    
}

This successfully creates a new window with the HTML in it. I have a bunch of HTML tags which when clicked run a function called Foo1. I've tried printing the entire function of Foo1 to the new HTML document, and tried putting Foo1 inside myScript.js. I see both Foo1 inside a script tag in the new window, and but neither are loaded since they are just written to the new page as HTML.

like image 935
user3333134 Avatar asked Sep 02 '15 15:09

user3333134


3 Answers

Just in case someone has this to be done in a link. Do the following:

<a href="javascript: var n= window.open('/url/to/page/in/SAMEDOMAIN'); n.focus(); n.addEventListener('load', n.alert('replace this with a good thing'), true);">Link</a>

This opens a new window with that URL, it set the focus to that windows, and as soon as the 'load' event is triggered, it executes the code in the function. It only works with a page in the same domain.

Hope this helps ⬆✌.

Cheers 👍

like image 170
Andrés Villenas Avatar answered Oct 24 '22 06:10

Andrés Villenas


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 = '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.

like image 40
Barmar Avatar answered Oct 24 '22 04:10

Barmar


Try this:

var newWindow = window.open('');
newWindow.document.createElement('script');
script.src = 'js/myScript.js';
newWindow.document.head.appendChild(script);
like image 26
LostMyGlasses Avatar answered Oct 24 '22 06:10

LostMyGlasses