I need to set the onload attribute for a newly popped-up window. The following code works for Firefox:
<a onclick="printwindow=window.open('www.google.com');printwindow.document.body.onload=self.print();return false;" href='www.google.com'>
However, when I try this in IE, I get an error - "printwindow.document.body null or not defined'
The goal is to pop open a new window, and call up the print dialog for that window once it's been opened.
Any clues on how to make this work? It is important not to use javascript elsewhere on the target page, as I do not have control over it. All functionality must be contained in the link I posted above.
Check our jQuery. Particularly the document ready feature.
http://docs.jquery.com/Tutorials:How_jQuery_Works#Launching_Code_on_Document_Ready
While earlier answers correctly stated the new window must be from the same domain, they incorrectly answered why he got the error 'printwindow.document.body null or not defined'. It's because IE doesn't return any status from window.open() which means you can open a page and try to access it BEFORE onload is available.
For this reason you need to use something like setTimeout to check. For example:
This is further discussed here
onload is a property if window objects, not body elements, despite what the HTML attribute might lead you to believe. This is the reference:
However, in this context you can't pass it a string of JavaScript - you need to hand it a function. So, the full script like would look like this
Now, putting it all together
HOWEVER! This will not work for you for the URL "www.google.com". The browser security model prevents parent windows from accessing the window objects of child windows, UNLESS they both reside @ the same domain name.
This is not possible unless both pages are on the same domain. Your code does not work in FF, but rather prints the current page. If the pages are on the same domain, then you would write:
The final (admittedly, poor) solution that worked for all browsers was to use setTimeout and call print() that way, instead of modifying the onload attribute:
You are relying on "printwindow.document.body.onload=self.print();" line being executed before the child document finishes loading. I don't think you can be guaranteed that.
Here's an idea: prepare HTML or a page that has nothing but the page you need in an iframe. This page will have body.onload=self.print().