I have a tab open when the user clicks a button. On the onload I have it bring up the print dialog, but the user asked me whether it was possible that after it sends to the printer to print, if the tab could close itself. I am not sure whether this can be done. I have tried using setTimeout();, but it's not a defined period of time since the user might get distracted and have to reopen the tab. Is there any way to accomplish this?
if you try to close the window just after the print() call, it may close the window immediately and print() will don't work. This is what you should not do:
window.open();
...
window.print();
window.close();
This solution will work in Firefox, because on print() call, it waits until printing is done and then it continues processing javascript and close() the window.
IE will fail with this because it calls the close() function without waiting for the print() call is done. The popup window will be closed before printing is done.
One way to solve it is by using the "onafterprint" event but I don' recommend it to you becasue these events only works in IE.
The best way is closing the popup window once the print dialog is closed (printing is done or cancelled). At this moment, the popup window will be focussed and you can use the "onfocus" event for closing the popup.
To do this, just insert this javascript embedded code in your popup window:
<script type="text/javascript">
window.print();
window.onfocus=function(){ window.close();}
</script>
Hope this hepls ;-)
Update:
For new chrome browsers it may still close too soon see here. I've implemented this change and it works for all current browsers: 2/29/16
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
This is what I came up with, I don't know why there is a small delay before closing.
window.print();
setTimeout(window.close, 0);
Sure this is easily resolved by doing this:
<script type="text/javascript">
window.onafterprint = window.close;
window.print();
</script>
Or if you want to do something like for example go to the previous page.
<script type="text/javascript">
window.print();
window.onafterprint = back;
function back() {
window.history.back();
}
</script>
Just:
window.print();
window.close();
It works.
I just want to write what I have done and what has worked for me (as nothing else I tried had worked).
I had the problem that IE would close the windows before the print dialog got up.
After a lot of trial and error og testing this is what I got to work:
var w = window.open();
w.document.write($('#data').html()); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick
w.focus();
w.print();
w.close();
This seems to work in all browsers.
This code worked perfectly for me:
<body onload="window.print()" onfocus="window.close()">
When the page opens it opens the print dialog automatically and after print or cancel it closes the window.
Hope it helps,
Just wrap window.close by onafterprint event handler, it worked for me
printWindow.print();
printWindow.onafterprint = () => printWindow.close();
This is a cross-browser solution already tested on Chrome, Firefox, Opera by 2016/05.
Take in mind that Microsoft Edge has a bug that won't close the window if print was cancelled. Related Link
var url = 'http://...';
var printWindow = window.open(url, '_blank');
printWindow.onload = function() {
var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);
if (isIE) {
printWindow.print();
setTimeout(function () { printWindow.close(); }, 100);
} else {
setTimeout(function () {
printWindow.print();
var ival = setInterval(function() {
printWindow.close();
clearInterval(ival);
}, 200);
}, 500);
}
}
Using Chrome I tried for a while to get the window.onfocus=function() { window.close(); } and the
<body ... onfocus="window.close()">
to work. My results:
I had closed my print dialogue, nothing happened.
I changed window/tabs in my browser, still nothing.
changed back to my first window/tab and then the window.onfocus event fired closing the window.
I also tried <body onload="window.print(); window.close()" > which resulted in the window closing before I could even click anything in the print dialogue.
I couldn't use either of those.
So I used a little Jquery to monitor the document status and this code works for me.
<script type="text/javascript">
var document_focus = false; // var we use to monitor document focused status.
// Now our event handlers.
$(document).focus(function() { document_focus = true; });
$(document).ready(function() { window.print(); });
setInterval(function() { if (document_focus === true) { window.close(); } }, 500);
</script>
Just make sure you have included jquery and then copy / paste this into the html you are printing. If the user has printed, saved as PDF or cancelled the print job the window/tab will auto self destruct. Note: I have only tested this in chrome.
Edit
As Jypsy pointed out in the comments, document focus status is not needed. You can simply use the answer from noamtcohen, I changed my code to that and it works.
This works well in Chrome 59:
window.print();
window.onmousemove = function() {
window.close();
}
This worked for me 11/2020 <body onafterprint="window.close()"> ... simple.
this one works for me:
<script>window.onload= function () { window.print();window.close(); } </script>
The following worked for me:
function print_link(link) {
var mywindow = window.open(link, 'title', 'height=500,width=500');
mywindow.onload = function() { mywindow.print(); mywindow.close(); }
}
REF source reference
<script type="text/javascript">
window.print();
window.onafterprint = window.close;
</script>
I tried many things that didn't work.
The only thing that worked for me was:
window.print();
window.onafterprint = function () {
window.close();
}
tested on chrome.
The following solution is working for IE9, IE8, Chrome, and FF newer versions as of 2014-03-10.
The scenario is this: you are in a window (A), where you click a button/link to launch the printing process, then a new window (B) with the contents to be printed is opened, the printing dialog is shown immediately, and you can either cancel or print, and then the new window (B) closes automatically.
The following code allows this. This javascript code is to be placed in the html for window A (not for window B):
/**
* Opens a new window for the given URL, to print its contents. Then closes the window.
*/
function openPrintWindow(url, name, specs) {
var printWindow = window.open(url, name, specs);
var printAndClose = function() {
if (printWindow.document.readyState == 'complete') {
clearInterval(sched);
printWindow.print();
printWindow.close();
}
}
var sched = setInterval(printAndClose, 200);
};
The button/link to launch the process has simply to invoke this function, as in:
openPrintWindow('http://www.google.com', 'windowTitle', 'width=820,height=600');
<!doctype html>
<html>
<script>
window.print();
</script>
<?php
date_default_timezone_set('Asia/Kolkata');
include 'db.php';
$tot=0;
$id=$_GET['id'];
$sqlinv="SELECT * FROM `sellform` WHERE `id`='$id' ";
$resinv=mysqli_query($conn,$sqlinv);
$rowinv=mysqli_fetch_array($resinv);
?>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1px'>Veg/NonVeg</td>
</tr>
<tr>
<th style='text-align:center;font-sie:4px'><b>HARYALI<b></th>
</tr>
<tr>
<td style='text-align:center;font-sie:1px'>Ac/NonAC</td>
</tr>
<tr>
<td style='text-align:center;font-sie:1px'>B S Yedurappa Marg,Near Junne Belgaon Naka,P B Road,Belgaum - 590003</td>
</tr>
</table>
<br>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1'>-----------------------------------------------</td>
</tr>
</table>
<table width="100%" cellspacing='6' cellpadding='0'>
<tr>
<th style='text-align:center;font-sie:1px'>ITEM</th>
<th style='text-align:center;font-sie:1px'>QTY</th>
<th style='text-align:center;font-sie:1px'>RATE</th>
<th style='text-align:center;font-sie:1px'>PRICE</th>
<th style='text-align:center;font-sie:1px' >TOTAL</th>
</tr>
<?php
$sqlitems="SELECT * FROM `sellitems` WHERE `invoice`='$rowinv[0]'";
$resitems=mysqli_query($conn,$sqlitems);
while($rowitems=mysqli_fetch_array($resitems)){
$sqlitems1="SELECT iname FROM `itemmaster` where icode='$rowitems[2]'";
$resitems1=mysqli_query($conn,$sqlitems1);
$rowitems1=mysqli_fetch_array($resitems1);
echo "<tr>
<td style='text-align:center;font-sie:3px' >$rowitems1[0]</td>
<td style='text-align:center;font-sie:3px' >$rowitems[5]</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[4],2)."</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[6],2)."</td>
<td style='text-align:center;font-sie:3px' >".number_format($rowitems[7],2)."</td>
</tr>";
$tot=$tot+$rowitems[7];
}
echo "<tr>
<th style='text-align:right;font-sie:1px' colspan='4'>GRAND TOTAL</th>
<th style='text-align:center;font-sie:1px' >".number_format($tot,2)."</th>
</tr>";
?>
</table>
<table width="100%">
<tr>
<td style='text-align:center;font-sie:1px'>-----------------------------------------------</td>
</tr>
</table>
<br>
<table width="100%">
<tr>
<th style='text-align:center;font-sie:1px'>Thank you Visit Again</th>
</tr>
</table>
<script>
window.close();
</script>
</html>
Print and close new tab window with php and javascript with single button click
This works for me perfectly #holger, however, i have modified it and suit me better, the window now pops up and close immediately you hit the print or cancel button.
function printcontent()
{
var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=300, height=350, left=50, top=25";
var content_vlue = document.getElementById("content").innerHTML;
var w = window.open("","", disp_setting);
w.document.write(content_vlue); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick
w.focus();
w.print();
w.close();
}"
jquery:
$(document).ready(function(){
window.print();
setTimeout(function(){
window.close();
}, 3000);
});
This worked best for me injecting the HTML into the popup such as <body onload="window.print()"...
The above works for IE, Chrome, and FF (on Mac) but no FF on Windows.
https://stackoverflow.com/a/11782214/1322092
var html = '<html><head><title></title>'+
'<link rel="stylesheet" href="css/mycss.css" type="text/css" />'+
'</head><body onload="window.focus(); window.print(); window.close()">'+
data+
'</body></html>';
Here's what I do....
Enable window to print and close itself based on a query parameter.
Requires jQuery. Can be done in _Layout or master page to work with all pages.
The idea is to pass a param in the URL telling the page to print and close, if the param is set then the jQuery “ready” event prints the window, and then when the page is fully loaded (after printing) the “onload” is called which closes the window. All this seemingly extra steps are to wait for the window to print before closing itself.
In the html body add and onload event that calls printAndCloseOnLoad(). In this example we are using cshtm, you could also use javascript to get param.
<body onload="sccPrintAndCloseOnLoad('#Request.QueryString["PrintAndClose"]');">
In the javascript add the function.
function printAndCloseOnLoad(printAndClose) {
if (printAndClose) {
// close self without prompting
window.open('', '_self', ''); window.close();
}
}
And jQuery ready event.
$(document).ready(function () {
if (window.location.search.indexOf("PrintAndClose=") > 0)
print();
});
Now when opening any URL, simply append the query string param “PrintAndClose=true” and it will print and close.
To me, my final solution was a mix of several answers:
var newWindow = window.open();
newWindow.document.open();
newWindow.document.write('<html><link rel="stylesheet" href="css/normalize-3.0.2.css" type="text/css" />'
+ '<link rel="stylesheet" href="css/default.css" type="text/css" />'
+ '<link rel="stylesheet" media="print" href="css/print.css" type="text/css" />');
newWindow.document.write('<body onload="window.print();" onfocus="window.setTimeout(function() { window.close(); }, 100);">');
newWindow.document.write(document.getElementById(<ID>).innerHTML);
newWindow.document.write('</body></html>');
newWindow.document.close();
newWindow.focus();
This is what worked for me (2018/02). I needed a seperate request because my print wansn't yet on screen.
Based on some of the excellent responses above, for which i thank you all, i noticed:
w.onload must not be set before w.document.write(data).
It seems strange because you would want to set the hook beforehand. My guess: the hook is fired already when opening the window without content. Since it's fired, it won't fire again. But, when there is still processing going on with a new document.write() then the hook will be called when processing has finished.
w.document.close() still is required. Otherwise nothing happens.
I've tested this in Chrome 64.0, IE11 (11.248), Edge 41.16299 (edgeHTML 16.16299), FF 58.0.1 .
They will complain about popups, but it prints.
function on_request_print() {
$.get('/some/page.html')
.done(function(data) {
console.log('data ready ' + data.length);
var w = window.open();
w.document.write(data);
w.onload = function() {
console.log('on.load fired')
w.focus();
w.print();
w.close();
}
console.log('written data')
//this seems to be the thing doing the trick
w.document.close();
console.log('document closed')
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a onclick="on_request_print();">Print rapportage</a>
const printHtml = async (html) => {
const printable = window.open('', '_blank', 'fullscreen=no');
printable.document.open();
printable.document.write(`<html><body onload="window.print()">${html}</body></html>`);
await printable.print();
printable.close();
};
Here's my ES2016 solution.
IE had (has?) the onbeforeprint and onafterprint events: you could wait for that, but it would only work on IE (which may or may not be ok).
Alternatively, you could try and wait for the focus to return to the window from the print dialog and close it. Amazon Web Services does this in their invoice print dialogs: you hit the print button, it opens up the print-friendly view and immediately opens up the printer dialog. If you hit print or cancel the print dialog closes and then the print-friendly view immediately closes.
There's lots of pain getting stuff like this to work across browsers.
I was originally looking to do the same sort of thing - open a new page styled for print, print it using JS, then close it again. This was a nightmare.
In the end, I opted to simply click-through to the printable page and then use the below JS to initiate a print, then redirect myself to where I wanted to go when done (with a variable set in PHP in this instance).
I've tested this across Chrome and Firefox on OSX and Windows, and IE11-8, and it works on all (although IE8 will freeze for a bit if you don't actually have a printer installed).
Happy hunting (printing).
<script type="text/javascript">
window.print(); //this triggers the print
setTimeout("closePrintView()", 3000); //delay required for IE to realise what's going on
window.onafterprint = closePrintView(); //this is the thing that makes it work i
function closePrintView() { //this function simply runs something you want it to do
document.location.href = "'.$referralurl.'"; //in this instance, I'm doing a re-direct
}
</script>
just use this java script
function PrintDiv() {
var divContents = document.getElementById("ReportDiv").innerHTML;
var printWindow = window.open('', '', 'height=200,width=400');
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
printWindow.close();
}
it will close window after submit or cancel button click
On IE11 the onfocus event is called twice, thus the user is prompted twice to close the window. This can be prevented by a slight change:
<script type="text/javascript">
var isClosed = false;
window.print();
window.onfocus = function() {
if(isClosed) { // Work around IE11 calling window.close twice
return;
}
window.close();
isClosed = true;
}
</script>
This worked for me in FF 36, Chrome 41 and IE 11. Even if you cancel the print, and even if you closed the print dialog with the top-right "X".
var newWindow=window.open();
newWindow.document.open();
newWindow.document.write('<HTML><BODY>Hi!</BODY></HTML>'); //add your content
newWindow.document.close();
newWindow.print();
newWindow.onload = function(e){ newWindow.close(); }; //works in IE & FF but not chrome
//adding script to new document below makes it work in chrome
//but alone it sometimes failed in FF
//using both methods together works in all 3 browsers
var script = newWindow.document.createElement("script");
script.type = "text/javascript";
script.text = "window.close();";
newWindow.document.body.appendChild(script);
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
It's work perfectly for me.
Hope it helps
Related
I made a new window using window.open(); and I want to close it. So I made this code.
$('#open').on('click', function () {
var win = window.open("", "", "width=400, height=200");
$newWindow = $(win.document.body);
// more code
$newWindow.find('#close').on('click', function () {
win.close(); // just works once
});
});
And it works good in FF, works just once in Chrome (close button stops working), and does not work on IE11 (just tested v11)...
What am I doing wrong? ie, how to fix this to work cross browser?
jsFiddle
The problem is with this line:
$newWindow.html(content);
You need to clone the element before you add it to the popup. Otherwise you are removing the original element and moving it to the new spot.
$newWindow.html(content.clone());
Updated Fiddle: http://jsfiddle.net/XL7LR/10/
I haven't been able to make sense of the answers to related questions so far(down to my knowledge level), so...
I have a simple script(using jQuery) that opens a new window and adds certain content from the parent into a specified container inside the child. I'm not sure if it's my approach that's wrong or I'm just missing a step - the script to run on the new window runs in IE when it's outside of the window.onload function, but this breaks FF, and FF is happy when it's inside of the window.onload, but then the new window in IE doesn't appear to be doing anything(no alert, no add of content, nada).
Please can anybody explain to me why this is the case/what I'm doing wrong? Is it something to do with the reference to window.open?
This is the script:
var printPage = function(container){
$('.printButton').click(function(){
var printWindow = window.open('printWindow.html');
var contentFromParent = $(container).eq(0).html();
/*works for IE, but not FF
printWindow.alert('works for IE, but not FF');
printWindow.document.getElementById('wrap').innerHTML = contentFromParent;*/
/*works for FF and Chrome but not IE:*/
printWindow.onload = function(){
printWindow.alert('works for FF and Chrome but not IE');
printWindow.document.getElementById('wrap').innerHTML = contentFromParent;
}
/*I also tried:
$(printWindow.document).ready(function(){
printWindow.alert('load the page, fill the div');
printWindow.document.getElementById('wrap').innerHTML = contentFromParent;
}); //works for IE, not working for FF/Chrome*/
})
}
printPage('#printableDiv');
The HTML:
<div id="wrap">
<button href="#" class="printButton">Print</button>
<div id="printableDiv">
<p>I want to see this content in my new window please</p>
</div>
</div>
UPDATE
Thanks for your pointers about onload in the new window - I've gone with this solution for now: Setting OnLoad event for newly opened window in IE6 - simply checking the DOM and delaying the onload - working for IE7/8/9.
I'm not sure if you'd call it an 'elegant' solution, but it's working! Further comments, especially if you think this is flawed, would be appreciated. Thanks.
var newWinBody;
function ieLoaded(){
newWinBody = printWindow.document.getElementsByTagName('body');
if (newWinBody[0]==null){
//page not yet ready
setTimeout(ieLoaded, 10);
} else {
printWindow.onload = function(){
printWindow.alert('now working for all?');
printWindow.document.getElementById('wrap').innerHTML = contentFromParent;
}
}
}
IEloaded();
Can it be that the page you open fires the 'onload' event before you set the event handler printWindow.onload = ... ?
You might consider including some javascript in your 'printWindow.html' page. Let's say you add a short <script>var printWindowLoaded = true;</script> at the end of your page. Then your main script would do something like this:
function doStuff() {
//...
}
if (printWindow.printWindowLoaded)
doStuff();
else
printWindow.onload = doStuff;
I want to open a window on click, but I want to open it behind the current window, or when the new window opens it should minimize itself. I have made a function but it actually did not work.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function wn(){
var mm=window.open('http://www.google.com','newwindow','width=200, height=200', "_blank");
}
</script>
</head>
<body>
click
</body>
EDIT
Parent window HTML
<script language="JavaScript" type="text/javascript">
function openPopUP() {
window.open('mywindow.html','NewWin',
'toolbar=no,status=no,width=350,height=135')
}
</script>
<body onLoad="openPopUP();">
or
Click to open popup
Child Window i.e PopUp Window File
The below script should be in the child window. The child window will open and will automatically be hidden after 1 second. The value 1000 specified in the setTimeout method is the duration in milliseconds for which the child window will be open. You can increase this timeout duration if you want the child window to be open longer.
<body onLoad="setTimeout('window.blur()', 1000);"
onFocus="setTimeout('window.blur()', 1000);">
This might work for you: Add this line of code in the onload event of your child window...
window.parent.opener.focus();
popunder = window.open('http://www.google.com','newwindow','width=200, height=200', "_blank");
popunder.blur();
window.focus();
Try something like this.
window.open(url);
self.focus();
Although it causes security issues, but I guess one of the way to do it is :
popup = window.open('http://www.google.com', 'newwindow', "_blank");
popup.blur();
This will work only in IE. For other browsers you need to set the security level to minimum.
popunder = window.open('your_site_url','newwindow','width=500, height=500', "_blank");
popunder.blur();
window.focus();
or simply
window.open(url); self.focus();
If you want real popunder capabilities there is a great jQuery plugin to handle it at https://github.com/hpbuniat/jquery-popunder
It uses a combination of various techniques to accomplish it across various browsers. Not all browsers can handle it the same but the results are very similar.
Current browser compatibility is listed as: (last updated April '18)
Mozilla Firefox 3-57
Google Chrome 10-62
Microsoft Internet Explorer 6-11 -- MSIE 6-8 requires jquery 1.x
Apple Safari 5
Finally , it was working for me only in chrome browser. Add this code in Parent window:
<script type="text/javascript" language="javascript">
function popWindow()
{
var popupo = window.open("popup.html", 'newwindow','toolbar=no,status=no,width=650,height=450', "_blank");
popupo.moveTo(0, 0);
popunder.blur();
window.focus();
}
</script>
Add this code in child window body onload event as
<body onLoad="setTimeout('window.blur()', 1000);" onFocus="setTimeout('window.blur()', 1000);">
Insted of a new window, we can create an iframe and open your url in the iframe and then make the iframe display none also print the iframe content if you want.
var ifrmId = 1;
jQuery(document).on('click', '.myFunc', function(e) {
var url = 'www.xyz.com';
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", url);
ifrm.setAttribute("id", ifrmId);
document.body.appendChild(ifrm);
window.frames[ifrmId].focus();
window.frames[ifrmId].contentWindow.print();
document.getElementById(ifrmId).style.display = "none";
ifrmId = ifrmId + 1;
});
why the following code works in safari but not in IE6 ? It opens the window but doesnt trigger the alert.
<script>
function fnOpenChild()
{
var openChild = window.open('child.htm');
openChild.onload = function() {
alert("im the child window");
};
}
</script>
<input type="button" onClick="fnOpenChild()">
Thank You
try it!
to move onload event to child.htm
I know this isn't actually an answer, but I really suggest you don't use IE6 anymore, and just go with IE8+.
Afterwards, add code that will warn the user that he/she is using an out-dated web browser. You can detect the browser version using navigator.appVersion
If you want to know why you or anyone else shouldn't use it anymore:
http://www.google.nl/#hl=nl&source=hp&biw=1024&bih=837&q=Why+IE6+must+die
Edit: Aah, I guess you fixed it, but I still suggest you take a look at the link above. :)
IE6 has some... rather interesting issues and it requires some workarounds. Have you tried googleing, "IE6 window onload"? http://www.webdeveloper.com/forum/showthread.php?t=183578 seems to have a working suggestion.
Try applying onreadystatechange as well. IE6 has some issue with onload.
openChild.onload = openChild.onreadystatechange = function() { ...
There could be two possible work-arounds:
1. Move the onload script ot the childwindow
**child.htm**
<html>
<script type="text/javascript">
window.onload = function(){
alert('im the child window');
}
</script>
<body>
....
</body>
</html>
2. Declare a function in the opener window and call it on the the child's onload
**parent.htm**
<script type="text/javascript">
function forChildWindow(params){
alert('im the child window' + params);
}
</script>
**child.htm**
<html>
<script type="text/javascript">
window.onload = function(){
var load = window.opener.forChildWindow;
var someparams = " param1";
if(load) {
load(someparams);
}
}
</script>
<body>
....
</body>
</html>
I'm trying to launch a popup window from a Javascript function and ensure it has focus using the following call:
window.open(popupUrl, popupName, "...").focus();
It works in every other browser, but IE8 leaves the new window in the background with the flashing orange taskbar notification. Apparently this is a feature of IE8:
http://msdn.microsoft.com/en-us/library/ms536425(VS.85).aspx
It says that I should be able to focus the window by making a focus() call originating from the new page, but that doesn't seem to work either. I've tried inserting window.focus() in script tags in the page and the body's onload but it has no effect. Is there something I'm missing about making a focus() call as the page loads, or another way to launch a popup that IE8 won't hide?
The IE8 is not allowing this feature because of security issues
Windows Internet Explorer 8 and later. The focus method no longer brings child windows (such as those created with the open method) to the foreground. Child windows now request focus from the user, usually by flashing the title bar. To directly bring the window to the foreground, add script to the child window that calls the focus method of its window object
http://msdn.microsoft.com/en-us/library/ms536425%28VS.85%29.aspx
You might try this. Not sure if it will work though>
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var hasFocus = true;
var active_element;
function setFocusEvents() {
active_element = document.activeElement;
if (isIE) {
document.onfocusout = function() { onWindowBlur(); }
document.onfocusin = function() { onWindowFocus(); }
} else {
window.onblur = function() { onWindowBlur(); }
window.onfocus = function() { onWindowFocus(); }
}
}
function onWindowFocus() {
hasFocus = true;
}
function onWindowBlur() {
if (active_element != document.activeElement) {
active_element = document.activeElement;
return;
}
hasFocus = false;
}
Yeah I can't test this on IE8 at the moment either but have a play with this document.ready method instead of the body.onload:
test1.html:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function openNewWindow()
{
window.open("test2.html", null, "height=200, width=200");
}
</script>
</head>
<body>
<a onclick="openNewWindow()">Open</a>
</body>
</html>
test2.html:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ window.focus(); });
</script>
</head>
<body>
<div id="container" style="background:blue;height:200px;width:300px">
</div>
</body>
</html>
I figured out what the issue was - turns out the reason running window.focus() in the onload wasn't working was because the first window.open().focus() call caused it to start flashing in the background, and after that any subsequent focus calls wouldn't work. If I don't try to focus it from the calling window but only from the popup it comes to the front normally. What an annoying "feature"...
The problem is the Window.focus method does not work in Internet Explorer 8 (IE 8). It's not a pop up blocker or any settings in IE 8 or above; it's due to some security I believe to stop annoying pop-ups being brought back up to the top.
after a lot of hair pulling and googling i found the following:
Microsoft suggest updates but this doesn't appear to work plus how do they seriously expect me to ask all of the users my site to update their machines!
so I've come up with this work around or fix.
What i do with the window is:
first I check if the window is open
if it's open, close it
open a new fresh version of the window on top.
javascript code to include at header or in separate file:
function nameoflink()
{
var nameofwindow = window.open('pagetolinkto.htm','nameofwindow','menubar=1,resizable=1,width=350,height=250');
if (nameofwindow) {
nameofwindow.close();
}
window.open('pagetolinkto.htm','nameofwindow,'menubar=1,resizable=1,width=350,height=250');
return false;
}
link on the page:
Click Here to go to name of link
Tested in MS Windows 7 with IE8 not sure of exact version.