Use anchor tag to open a blank window and write into it

1.6k Views Asked by At

I know that I can use <a href="" target="_blank"> to open a new window. I can also use onclick even handler to create the window and fill it with dynamic content, like win = open(""); win.document.innerHTML =. But, the latter forces me to use button and create window explicitly instead of relying on default <a> functionality. Can I combine them, to use <a> to open the window and it's onclick to fill it?

1

There are 1 best solutions below

8
On BEST ANSWER

win.body.innerHTML only works if you open a page that has a body. Some browsers might do that (open a dummy document) for you, but certainly not all

Here is a link - I use inline JS for demonstration, a better choice is to assign the onclick in onload of the page:

Here is a JSFiddle since the SO Snippet does not allow the popup

<a href="activateyourjsandallowpopups.html" 
onclick="var w = window.open('','_blank'); // may fail if blocked
if (w) { w.document.write('Hello'); w.document.close(); }     
return !w">Click</a>

Perhaps you mean this?

<a href="pagefrommyserver.html" target="myWin" 
onclick="setTimeout(function() { 
  var w = window.open('','myWin'); // get the opened window handle
  if (w) { w.document.body.innerHTML = 'Hello'}
},200)">Click</a>