Opening windows using javascript in guaranteed order - javascript

I have javascript that opens a list of URLs in their own windows. I can use window.open for each, but the problem is that sometimes, the browser doesn't always open the windows in the order I have asked them to be opened, especially when there is a large number of URLs. The URLs are not in my domain so I can't wait for an onLoad event from the child. Is there any way to determine if the child window is open before I open the next? As a last resort I guess I can create a wait time between each open, but that's more of a hack, slows everything down and while will probably make the correct order more likely, it won't guarantee it. For example:
<script type='text/javascript'>
var urls = new Array();
urls[0] = 'http://www.yahoo.com';
urls[1] = 'http://www.google.com';
urls[2] = 'http://www.facebook.com';
$(document).ready(function() {
for (i=0; i<urls.length; i++) {
window.open(urls[i]);
}
});
</script>

Okay, I figured it out. There is no way to see of a child window in a remote URL is open. That's true. However, if you open a file in your domain who's only job is to alert the parent that it's open, then redirect to the remote URL, that works. Something like this:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type='text/javascript'>
var urls = new Array();
urls[0] = 'http://www.yahoo.com';
urls[1] = 'http://www.google.com';
urls[2] = 'http://www.facebook.com';
urls[3] = 'http://www.linkedin.com';
urls[4] = 'http://www.twitter.com';
$(document).ready(function() {
var interval = null;
function doNext(i) {
if (i < urls.length) {
// console.log("Doing: " + i);
childWin = window.open('tst2.jsp?i=' + i + '&url=' + urls[i]);
interval = setInterval(function() {waitForIt(i);}, 1000);
waitForIt(i);
}
}
function waitForIt(i) {
if (document.getElementById("urls" + i).checked == false) {
// console.log('wait for: ' + i);
} else {
clearInterval(interval);
if (i < urls.length) {
doNext(i+1);
}
}
}
doNext(0);
});
</script>
<input type="checkbox" id="urls0">http://www.yahoo.com<br>
<input type="checkbox" id="urls1">http://www.google.com<br>
<input type="checkbox" id="urls2">http://www.facebook.com<br>
<input type="checkbox" id="urls3">http://www.linkedin.com<br>
<input type="checkbox" id="urls4">http://www.twitter.com<br>
then, in tst2.jsp, something like this:
<script>
opener.document.getElementById("urls" + <%=request.getParameter("i")%>).checked = true;
// console.log("Set variable");
window.location = '<%= request.getParameter("url") %>';
</script>
Also, one note, the number of windows you can open depends on the browser. Firefox can be configured to anything. It looks like Chrome is limited to 20. I'm not sure about IE.

You are probably limited in the number of windows you can open, they are probably being reused after a number of calls.
open() is supposed to be a blocking call, so it always waits until the browser has at least opened a new window before moving on to the next one.
You may try adding a random parameter as the second parameter to open to try to keep the browser from reusing windows if they were assigned default names.
// No guarantee that the name generated is unique, but if that's your only problem
// you should be OK
window.open(urls[i], "name" + new Date() + Math.random() );

Related

Second `window.location = mailto:` fails as long as first one is still open

I'm trying to open the local mail window using the javascript window.location.href=mailto:<addresses>. However, my addresses exceed the maximum length. So I slice it into pieces, and send these one after the other, after a specific timeout. However, the second relocation will not open a new (Outlook) mail window if the first is still open... Is there any way to get around this? Or is there another/better way to open multiple mail windows on the local client?
Any help would be greatly appreciated!
The code:
function Send_Mails(mails) {
var timeout = 2000;
var maxUrlCharacters = 1900;
var currIndex = 0;
var nextIndex = 0;
if (mails.length < maxUrlCharacters) {
window.location = 'mailto:' + mails;
return;
}
do {
currIndex = nextIndex;
nextIndex = mails.indexOf(';', currIndex + 1);
} while (nextIndex != -1 && nextIndex < maxUrlCharacters)
if (currIndex == -1) {
window.location = 'mailto:' + mails;
} else {
window.location = 'mailto:' + mails.slice(0, currIndex);
setTimeout(function () {
Send_Mails(mails.slice(currIndex + 1));
}, timeout);
}
}
This opens the first mailwindow correctly, but the second one is never opened as long as the first one is open.
Best regards,
Hans
The sample script below works for me on localhost
<button onclick="openmail()">Open mail</button>
<script>
function openmail(){
window.location.href="mailto:test1#test.org"
setTimeout(function(){
console.log('2nd email');
window.location.href="mailto:test2#test.org"
}, 3000);
}
</script>
When on Fiddle, it seems to be working 75% of the time (with ad blocker turned on).
There is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of multiple mailto links.

How to dynamically change tab title when it is not selected?

I want to display dynamic information (score) in the window tab of a javascript games running in a browser (chrome) : my goal is to run several instances of the game in different tabs, running in parallel, and to be able to see the current scores in the tab titles. I tried :
document.title = score
... but it works only in the selected tab, the other one are not refreshed until selected (although the games are running well in background).
==> is there a way to force the update of the tab titles... even if not selected ?
I found couple of same questions on the http://stackoverflow.com but they did not work for me.
You can find your solution here: http://www.raymondcamden.com/2010/10/19/Using-JavaScript-to-update-the-browser-window-title-when-the-user-is-away
So, basically that kind of code will work:
var focused = true;
var baseTitle = "";
var chatsMissed = 0;
//I'm the fake function that represents some process. We randomly determine if a new chat happened
function fakeStuff() {
if(Math.random() > 0.5) {
if(!focused) {
chatsMissed++;
window.document.title = baseTitle + " ("+chatsMissed+")";
}
}
}
$(document).ready(function() {
//store the base title
baseTitle = window.document.title;
//When the window is focused...
$(window).focus(function() {
focused = true;
// window.document.title = baseTitle;
//chrome bug: http://heyman.info/2010/oct/7/google-chrome-bug-when-setting-document-title/
setTimeout(function() {
document.title = baseTitle;
}, 100);
chatsMissed = 0;
});
//When the window is blurred...
$(window).blur(function() {
focused = false;
});
//setup a process
window.setInterval('fakeStuff()',2000);
})
Unfortunately JSfiddle do not support title changing. But I tested, and it works.

Why does calling a function onclick not work all the time in Chrome and FF, but works in IE?

I have the below code:
<HTML>
<HEAD>
<SCRIPT>
function myFunction(atlasTrackingURL)
{
var atlasURL = atlasTrackingURL;
if (!atlasURL) return;
//Build a cache busting mechanism
var timestamp = new Date();
var queryString = "?random=" + Math.ceil(Math.random() * 999999999999) +
timestamp.getUTCHours() + timestamp.getUTCMinutes() +
timestamp.getUTCSeconds();
//Build the final URL
atlasURL = atlasURL + queryString;
if (!document.getElementsByTagName || !document.createElement
|| !document.appendChild)
{return false;}
else
{ //Activate the JACTION call
var script = document.createElement("script");
script.type = "text/javascript";
script.src = atlasURL;
document.getElementsByTagName("head")[0].appendChild(script);
return true;
}
}
</SCRIPT>
</HEAD>
<BODY>
Test - Click Me
</BODY>
</HTML>
It works in Internet Explorer every time, but rarely works in Chrome and Firefox. Why would this be?
Can these browsers not handle a function onClick very well? Are there any other options I can take?
I am trying to help a client figure out why one of their tracking tags are not firing off all the time on click in these browsers.
Thanks,
You've got some kind of browser-dependent race condition going on, as Musa pointed out.
Try hiding the link initially, waiting for the document to load, and then adding the onclick attribute and revealing the link with javascript.
So, for example, change the link HTML to something like:
<a id="microsoft-link" href="http://www.microsoft.com" style="display: none;">Test - Click Me</a>
And add in your javascript, below the myFunction(), something like:
document.addEventListener('DOMContentLoaded', function(){
var link_elem = document.getElementById("microsoft-link");
link_elem.onclick = function() {
myFunction('http://view.atdmt.com/jaction/adoakb_PiggybackJSTest_1');
};
link_elem.style.display = 'inherit';
});
jsfiddle -- http://jsfiddle.net/m8VTy/3/
edit: I realized I may be misinterpreting what you're trying to do. What exactly is myFunction() supposed to accomplish ?

Check popup window status

When someone requests a chat, an entry is made in the database. I have an hidden iframe on our dashboard that checks the database every 20 seconds to see if there is a chat and if there is it launches a popup window. Even if the popup is open the iframe still refreshes the popup every 20 seconds. Want I am trying to achieve is a javascript to check the status of the popup. If it is closed I want it to reopen it... if it is open then it bring it into focus... but I dont want the popup to refresh.. as I have an ajax script doing this..
Here is my code:
<script language="javascript" type="text/javascript">
function myOpenWindow(winURL, winName, winFeatures, winObj)
{
var theWin;
if (winObj != null)
{
if (!winObj.closed)
{
winObj.focus();
return winObj;
}
}
else
{
theWin = window.open(winURL, winName, winFeatures);
return theWin;
}
}
</script>
<% IF ChatSessionID <> "" THEN %>
<script language="javascript" type="text/javascript">
var gmyWin = null;
window.onload = function()
{
var w = 900;
var h = 500;
var l = (screen.width-w)/2;
var t = (screen.height-h)/2;
var params = 'status=0,resizable=0,scrollbars=0,width=' + w + ',height=' + h + ',left=' + l + ',top=' + t;
gmyWin = myOpenWindow("/chat/chat_window.asp?ChatSession=<%=ChatSessionID%>&id=3", "myWin", params, gmyWin)
}
</script>
<% END IF %>
Any help you could provide would be greatly appreciated..
Best Regards,
Paul
I am not sure, but I believe if you name the window (e.g. myWin) when you call window.open, then later call window.open again using the same name, it will return the existing window if its already open or open/re-open the window and return a handle to that.
Edit
Ah, there you go -- from window.open:
If a window with the name
strWindowName already exists, then,
instead of opening a new window,
strUrl is loaded into the existing
window. In this case the return value
of the method is the existing window
and strWindowFeatures is ignored.
Providing an empty string for strUrl
is a way to get a reference to an open
window by its name without changing
the window's location. If you want to
open a new window on every call of
window.open(), you should use the
special value _blank for
strWindowName.
I believe according to the above mentioned specs, this might work:
var hChatWindow = window.open("", "ChatWindow", "whatever features"); // url intentionally left blank
// hChatWindow now contains a reference to new, existing or re-opened window
hChatWindow.focus();
if (hChatWindow.location=="about:blank") { // not sure; you need to experiment here
hChatWindow.location = "/chat/chat_window.asp?whatever";
}
Demo here, source here.
Register a callback on gmyWin.onunload.
You will find it tricky to subvert "block pop-up windows" in most browsers. However, if it is disabled, the following will work.
Main window:
var status = false;
function winOpen(){
window.open("child.html");
}
function winStatus(){
alert(status);
}
Pop-up window:
window.opener.status = true;
window.onblur = window.focus;
window.onunload = function(){
window.opener.status = false;
};

Using a bookmarklet to track a package

I'm trying to write a bookmarklet that tracks a package in the mail. First it checks to see if the tracking page is open, if not it opens it in a new tab, and then sets the value of the form to the tracking number. Finally, it submits the form. What I'm so far unable to do is set the value of the form in the case where the bookmarklet opens up a new tab.
Here's what I have:
javascript: (function(){
var trackingNumber = "/*tracking number*/";
var a = document.forms.trackingForm;
if ('http://fedex.com/Tracking' == document.location) {
trackingForm.trackNbrs.value = trackingNumber;
document.forms.trackingForm.submit();
}
else {
window.open('http://fedex.com/Tracking');
this.window.onload = function(){ //This seems to be the problem
trackingForm.trackNbrs.value = trackingNumber;
onload(document.forms.trackingForm.submit());
}
}
})();
Any ideas?
window.open opens a new window, so if this is going to work at all (I have little experience with bookmarklets), you would have to address the new window directly. Something like this:
else {
new_window = window.open('http://fedex.com/Tracking');
new_window.onload = function(){
new_window.document.trackingForm.trackNbrs.value = trackingNumber;
new_window.document.forms.trackingForm.submit();
// I didn't get at all what the onload() was for, re-add if necessary
}

Categories

Resources