0

I want adding and running external javascript file in new window.open() , so I tested the solution in Running Javascript in new window.open , but this solution doesn't work.

My code is here :

<input type="button" value="Open a window" onclick="openWindow();">

<script type="text/javascript">

function openWindow()
{
    //Open a new window :
    var win = window.open("");

    //Create script tag :
    var script = document.createElement('script');

    //Add external javascript file in src attribut of script tag :
    script.src = "script.js";

    //Append script tag to the new window :
    win.document.head.appendChild(script);  
}

</script>

The content of external javascript file called script.js is :

alert("It works !");

When you click the button, a new window is opened, but the external javascript file added is not executed.

So how to run the external javascript file added in new window opened ?

totoaussi
  • 712
  • 1
  • 11
  • 27
  • If you set the `script.src` to `"script.js"` and create the new window, the new window will try and look for a javascript file called `script.js` in it's own files. Since you've just created that window with no other files, it has no `script.js` file to read/load. Take a look at https://stackoverflow.com/questions/29909927/inject-an-opened-window-with-script – T. Dirks Oct 25 '18 at 14:50

2 Answers2

0

Use document.write

const win = window.open('')
win.document.open()

const html = `
  <html>
    <head>
      <script src="https://code.jquery.com/jquery-2.2.4.min.js"><\/script>
    </head>
    <body>
      <h1>Test</h1>
      <script>alert($('h1').text())<\/script>
    </body>
  </html>
`

win.document.write(html)
win.document.close()
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Try this

<script type="text/javascript">
function openWindow()
{
    //Open a new window :
    var win = window.open("");

    //Create script tag :
    var script = document.createElement('script'),
        div = document.createElement('div');
    //Add external javascript file in src attribut of script tag :
    script.src = "https://cdnjs.cloudflare.com/ajax/libs/preact/8.3.1/preact.min.js";
    script.type = "application/javascript";
    script.defer = true;
    div.appendChild(script);
    win.document.body.appendChild(div);  
}

</script>

In the new window open developer console and type preact you will see output like {h: ƒ, createElement: ƒ, cloneElement: ƒ, Component: ƒ, render: ƒ, …}

front_end_dev
  • 1,998
  • 1
  • 9
  • 14