How to open a new window and insert html into it using jQuery?

JavascriptJqueryHtml

Javascript Problem Overview


I am trying to open a new window from javascript but nothing is being inserted into the html:

var callScriptText = $('#callScriptText').html();
var url = '/Action/CallScript/?callScript=';

// Open the current call script in a new window
var openWindow = window.open(url, 'callScriptPopup', 'width = 500, height = 500');
$(openWindow).html(callScriptText);

Does anyone know why?

Javascript Solutions


Solution 1 - Javascript

Here's an example to open a new window with content using jQuery

<script>
function nWin() {
  var w = window.open();
  var html = $("#toNewWindow").html();

    $(w.document.body).html(html);
}

$(function() {
    $("a#print").click(nWin);
});​
</script>

<div id="toNewWindow">
    <p>Your content here</p>
</div>

<a href="javascript:;" id="print">Open</a>

EDIT: For those who say that this code doesn't work, here's a jsfiddle to try it http://jsfiddle.net/8dXvt/

Solution 2 - Javascript

Try this:

var x=window.open();
x.document.open();
x.document.write('content');
x.document.close();

I find it works in Chrome and IE.

Solution 3 - Javascript

Building upon @Emre's answer.

With javascript, you can chain, so I just modified the code to:

var x=window.open();
x.document.open().write('content');
x.close();

Also, to force it to a new window (not a new tab), give the first line dimensions. But it has to be the third argument. So change the first line to:

var x=window.open('','','width=600, height=600');

Solution 4 - Javascript

try:

var x = window.open('', '', 'location=no,toolbar=0');
x.document.body.innerHTML = 'content';

Solution 5 - Javascript

var codeContents = $("#contentsfornewWindow").html()
var win = window.open('', 'title', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1000,height=1000,left=200,top=70');

win.document.body.innerHTML = codeContents;

VS:

win.document.write(codeContents);

I have notice if there are iframes like youtubes videos , win.document.write loads the iframes where as document.body.innerHTML does not!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFairyQueenView Question on Stackoverflow
Solution 1 - JavascriptJuanmaView Answer on Stackoverflow
Solution 2 - JavascriptEmreView Answer on Stackoverflow
Solution 3 - JavascriptSablefosteView Answer on Stackoverflow
Solution 4 - JavascriptHasan A YousefView Answer on Stackoverflow
Solution 5 - JavascriptTejpal SharmaView Answer on Stackoverflow