I have some code to open a popup, then resize the it via certain element on the popup page. The following code work fine in Chrome and Firefox, but not IE.
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
newWin.onload= function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
};
In IE10 a popup will come but the window.load event will never fire.
I also try newWin.$(document).ready , but seems it is invalid.
Any suggestion?
This is an old problem in IE.
One of the best solution is to add new.
Normally we write
window.onload=function() { alert('hello');};
Replace it with
window.onload=new function() { alert('hello');};
Finally I resolve this via setTimeout to check whenever the element in popup is well-generated, then resize the popup window
var newWin ;
function openWindow(id) {
newWin = window.open(url,config,setting);
var resizePopup = function () {
newWin.resizeTo(newWin.document.getElementById("certainID").offsetWidth,100);
newWin.focus();
};
var tryResize = function(){
if(newWin.document.getElementById("certainID")==null){
setTimeout(function(){tryResize();},500);
}
else{
resizePopup();
}
}
tryResize();
};
If using setTimeout, may be popup perform resizing when window not finish loading yet. I think best solution is using setInterval and check whenever document.readyState==='complete" => call clearInterval() and run resize
Related
I am trying to print a table in a new window.
The thing is, print tries to print before the page is rendered.
I suspect document.write is asynchronous.
I tried to use document.outerHTML / document.innerHTML instead of document.write(), but the CSS/JS files are not being parsed correctly as CSS.
The table has images in cells which are being loaded from cache, also after window.print().
Please, any idea would be helpful.
function printData() {
let newWin = window.open("");
styles="";
//read styles in different page
Array.prototype.forEach.call(
document.querySelectorAll("link, style"),
function(el){
styles += (el.outerHTML);
});
//DOESNT WORK NOT RENDER STYLES
// newWin.document.document.querySelector("html").innerHTML=(styles + document.querySelector("table").outerHTML);
//THIS FINISHES RENDERING AFTER PRINT
newWin.document.write(styles + document.querySelector("table").outerHTML);
//DOESNT WORK
newWin.document.addEventListener("DOMContentLoaded", function(){
if(newWin.document.addEventListener === "loading"){
newWin.print();
}
//DOESNT WORK
newWin.window.onload= function(){
newWin.print();
}
//WORKS
setTimeout(function(){
newWin.print();
newWin.close();
}, 2000);
});
}
Try something like:
let printAndClose = '<script>onload = function() { window.print(); window.close(); }</sc' + 'ript>';
newWin.document.write(
styles +
document.querySelector("table").outerHTML) +
printAndClose
);
Use window.onload to fire your function since this waits for all of the content of the page to load and is widely supported.
I resolved the similar issue by appending the following code to the end of <body>. It works in IE11, Chrome and Firefox. Calling window.close() without wrapping in setTimeout() causes IE11 to close window before showing print dialog.
<script type="text/javascript">
setTimeout(function() {
window.print();
setTimeout(function() {window.close();});
});
</script>
I'm trying to change a href link programmatically (according to a result from an ajax async operation) and open it in a new window (I don't want to use window.open as it behaves like a popup and being blocked in IE).
The following code works only after clicking MANUALLY on the link for a second time, how can I make it work on the first click?
Simplified example:
trying to change href link dynamically
<script type="text/javascript">
document.getElementById('link').addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) //only preventDefault for the first time..
{
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
// --HERE I PERFORM AN AJAX CALL WHICH TAKES A WHILE AND BY ITS RESULT I DECIDE WHICH URL TO USE - BUT HERE I JUST USE IT HARDCODED--
document.getElementById('link').setAttribute("href", "http://google.com");
document.getElementById('link').click();
}
I organized your code in this jsFiddle: http://jsfiddle.net/mswieboda/Hhj4D/
The JavaScript:
var $link = document.getElementById('link');
$link.addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) {
//only preventDefault for the first time..
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
$link.setAttribute("href", "http://google.com");
$link.click();
}
This worked for me when I ran it. Hovering the link, you could see http://demo.com but clicking it takes you to http://google.com. Is this the desired functionality? You can definitely use the updateLink function any time (after an AJAX call) to change the href, also, you could probably set the _target in that function as well, makes more sense to me that way.
I have the code below which opens a child window and the child has a callback function to the parent to close the child window which is called with onLoad in the child.
The code works fine in Firefox and Chrome but not in IE.
Can anyone see where I am going wrong?
Parent JS
var wnd = null;
function openWnd()
{
wnd = window.open('http://www.example.com');
}
function closeWnd()
{
if (wnd != null) {
wnd.close();
}
}
Child JS
function parent_callback()
{
setTimeout(function (){ window.opener.closeWnd();}, 3000);
}
Why is IE always a pain for developers M$ needs to pull its fingure out :)
Thanks
Your child window is calling a function closePDF() but your parent window defines closeWnd(). I can't see how that would work in any browser yet you say it works in Chrome and FF? Maybe if you post some more of your code, e.g., the onload that you mention, or the closePDF() if there actually is one.
I've got a Jquery function that I wrote which blacks out the screen after a certain amount of inactivity, creates a pop-up that allows the user to click a button to stay logged in, and logs them out (closing the application window) if they do not respond in time.
The environment is ASP.NET (VB). We don't technically use master pages, but we do have a parent page in which our header, footer and nav reside, and my Jquery code is called from that window, loaded via an IFrame.
My problem is that if one is working in a child window, the parent window doesn't recognize that the system is in use, and will automatically engage at the allocated time.
I've tried everything under the sun I can think of and nothing works properly. My event handler is working, and it does call the parent window function, but the timer is not being reset.
I have this function in the parent window:
<script language="javascript" type="text/javascript">
function window.reportChildActivity() {
SESSION_ALIVE = true;
window.setTimeout("pop_init()", SESSION_TIME);
}
</script>
And this in the child window:
<script type="text/javascript">
$(document).bind("mousedown keydown blur", function() {
window.parent.reportChildActivity(); });
</script>
No matter how much I click or use keys in the child window, my Jquery timeout code is called when SESSION_TIME runs out the first time. And then I get multiple Jquery windows in my page telling me to click to continue. It's like the events are being buffered and when they fire these windows are all being spawned multiple times. Does anyone see from this what I'm doing wrong? Thanks!
---- EDIT -----
I'm adding my pop_init function and supporting functions for reference:
// remove all added objects and restart timer
function popup_remove() {
$("#popup_window").fadeOut("fast", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
//if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
$("body", "html").css({ height: "auto", width: "auto" });
$("html").css("overflow", "");
//}
window.setTimeout(pop_init, SESSION_TIME);
}
// session ajax call from button click
function session_refresh() {
SESSION_ALIVE = true;
$(".buttons").hide();
$("#popup_message").html("<center><br />Thank you! You may now resume using the application.<br /></center>");
window.setTimeout(popup_remove, 1000);
$("#popup_window").fadeOut("slow", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
window.setTimeout(pop_init, SESSION_TIME);
}
function popup_expired() {
if (!SESSION_ALIVE)
window.close();
}
// Main popup window handler
function pop_init() {
// show modal div
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
//$("#popup_overlay").click(popup_remove); // removed to make sure user clicks button to continue session.
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>Warning</h1>");
$("#popup_window").append("<p id='popup_message'>Your session is about to expire. Please click the button below to continue working without losing your session.</p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'><img src='images/green-checkmark.png' alt=''/> Continue Working</button></center></div>");
// attach action to button
$("#continue").click(session_refresh);
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
// set pop-up timeout
SESSION_ALIVE = false;
window.setTimeout(popup_expired, 30000);
}
try assigning the setTimeout to a global variable and clearing it each time eg:
var timer=false;
window.reportChildActivity = function() {
if(timer!==false) {
clearTimeout(timer);
}
SESSION_ALIVE = true;
timer=window.setTimeout(pop_init, SESSION_TIME);
}
example: http://jsfiddle.net/pB2hX/1/
I need to know if the user is currently viewing a tab or not in Google Chrome. I tried to use the events blur and focus binded to the window, but only the blur seems to be working correctly.
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
The focus event works weird, only sometimes. If I switch to another tab and back, focus event won't activate. But if I click on the address bar and then back on the page, it will. Or if I switch to another program and then back to Chrome it will activate if the tab is currently focused.
2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):
document.addEventListener('visibilitychange', function(){
document.title = document.hidden; // change tab text for demo
})
The code the original poster gives (in the question) now works, as of 2011:
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus() does not make this work automatically either. If anyone knows of a workaround, please mention.
The selected answer for the question Is there a way to detect if a browser window is not currently active? should work. It utilizes the Page Visibility API drafted by the W3C on 2011-06-02.
It might work after all, i got curious and wrote this code:
...
setInterval ( updateSize, 500 );
function updateSize(){
if(window.outerHeight == window.innerHeight){
document.title = 'not focused';
} else {
document.title = 'focused';
}
document.getElementById("arthur").innerHTML = window.outerHeight + " - " + window.innerHeight;
}
...
<div id="arthur">
dent
</div>
This code does precisly what you want, but on an ugly way. The thing is, Chrome seems to ignore the title change from time to time (when switching to the tab and holding the mouse down for 1 sec seems to always create this effect).
You will get different values on your screen, yet your title won't change.
conclusion:
Whatever you are doing, don't trust the result when testing it!
For anyone who wants to swap page titles on blur and then go back to the original page title on focus:
// Swapping page titles on blur
var originalPageTitle = document.title;
window.addEventListener('blur', function(){
document.title = 'Don\'t forget to read this...';
});
window.addEventListener('focus', function(){
document.title = originalPageTitle;
});
I found that adding onblur= and onfocus= events to inline bypassed the issue:
This could work with JQuery
$(function() {
$(window).focus(function() {
console.log('Focus');
});
$(window).blur(function() {
console.log('Blur');
});
});
In chrome you can run a background script with a timeout of less than 1 second, and when the tab does not have focus chrome will only run it every second. Example;
This doesn't work in Firefox or Opera. Don't know about other browsers, but I doubt it works there too.
var currentDate = new Date();
var a = currentDate.getTime();
function test() {
var currentDate = new Date();
var b = currentDate.getTime();
var c = b - a;
if (c > 900) {
//Tab does not have focus.
} else {
//It does
}
a = b;
setTimeout("test()",800);
}
setTimeout("test()",1);