Window.open only if the window is not open - javascript

I have a link on my site that opens a new window to a page that plays a very long audio file. My current script works fine to open the page and not refresh if the link is clicked multiple times. However, when I have moved to a seperate page on my site and click this link again, it reloads. I am aware that when the parent element changes, I will lose my variable and thus I will need to open the window, overiding the existing content. I am trying to find a solution around that. I would prefer not to use a cookie to achieve this, but I will if required.
My script is as follows:
function OpenWindow(){
if(typeof(winRef) == 'undefined' || winRef.closed){
//create new
winRef = window.open('http://samplesite/page','winPop','sampleListOfOptions');
} else {
//give it focus (in case it got burried)
winRef.focus();
}
}

You should first to call winRef = window.open("", "winPopup") without URL - this will return a window, if it exists, without reloading. And only if winRef is null or empty window, then create new window.
Here is my test code:
var winRef;
function OpenWindow()
{
if(typeof(winRef) == 'undefined' || winRef.closed)
{
//create new
var url = 'http://someurl';
winRef = window.open('', 'winPop', 'sampleListOfOptions');
if(winRef == null || winRef.document.location.href != url)
{
winRef = window.open(url, 'winPop');
}
}
else
{
//give it focus (in case it got burried)
winRef.focus();
}
}
It works.

Thanks to Stan and http://ektaraval.blogspot.ca/2011/05/how-to-set-focus-to-child-window.html
My solution creates a breakout pop-up mp3 player that remains active site wide and only refreshes if the window is not open prior to clicking the link button
function OpenWindow(){
var targetWin = window.open('','winPop', 'sample-options');
if(targetWin.location == 'about:blank'){
//create new
targetWin.location.href = 'http://site/megaplayer';
targetWin.focus();
} else {
//give it focus (in case it got burried)
targetWin.focus();
}
}

Like you said, after navigating away from original page you're losing track of what windows you may have opened.
As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.

Related

window.open remove reference from parent

I have one page with list of reports and after clicking on report it redirects me to internal report page in new tab with:
window.open(reportIdUrl,reportId);
So when i am back on report list and i want to open same report i will use
window.open("",reportId);
if(redirect.location.href === "about:blank" || redirect.location.href !== '<internalreportpage>') {
redirect = window.open(reportUrl,reportId);
redirect.focus();
} else {
redirect.focus();
}
But when someone from new tab with internal report page navigates somehow to report list page (within this tab) and then tries to open internal report page it will open it in same tab as it is tab reference not content reference.
Does anybody know some way to drop reference when i access if condition?
Something like:
window.open("",reportId);
if(redirect.location.href === "about:blank" || redirect.location.href !== '<internalreportpage>') {
window.dropReference(reportId) //change_me
redirect = window.open(reportUrl,reportId);
redirect.focus();
} else {
redirect.focus();
}
So it will create new tab with new reportId reference?
Thanks
EXAMPLE
--reportlistpage
linkToReport1 (window.open(report1Url,1))
linkToReport2 (window.open(report2Url,2))
.
.
.
You click on linkToReport1 - 2 tabs are opened. One with reportlistpage and one with internal-report/report1.
You go back to parent tab and click to linkToReport1. Tab is opened with reference to "1" and will focus to it and no new tab is opened (this is ok).
You are on linkToReport1 and you redirect with some menu hyperlink to reportlistpage (within linkToReport1 tab). Url changed to /report-list
You click to linkToReport1. Nothing happen (this is not ok) because you are on the tab with reference to 1 (content and url changed), now you want to open a new tab with /internal-report/report1 url and store it as 1 with window references.
I figured it out. It is bit simple when you realize you can set or reset window.name. So there is nothing like references from parent.
Based on content you can do something following. In the page you want to keep track in tab,
at the beginning (in my case internalReport id):
var currentWindow = window.self;
currentWindow.name = reportId; //this is in case someone manually opened it without window.open(internalReportUrl, reportId)
then bind resetting of window.name on beforeunload event (e.g.):
var resetWindowName = function() {
var currentWindow = window.self;
currentWindow.name = ""
}
window.addEventListener('beforeunload', resetWindowName);
So when you redirect from internalreportpage somewhere, name is cleared and you can repeadetly call
window.open(internalReportUrl,reportId)
which will open new tab for you.

JavaScript with multiple popups

I am trying to open a new pop up for my application, and each popup has a window name. Suppose if the user closes the popup he can open the popup with same name, else the existing pop up should be displayed.
I wrote the below code to do that, but this is not opening a popup if the user closes it else its opening a new popup. Please suggest how can go with this.
d='javascript:if(document.getElementsByTagName("*").length>0&&document.getElementsByTagName("body")[0].innerHTML!=""&&!confirm("You are about to navigate to home page Do you want to do that ? "))
{opener.display2WindowHelp();}
else
{window.location.replace("${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}'+d+'");
}';
b= window.open(d,"_spor_window_"+a+window.location.hostname.replace(/\./g,""),"menubar=no,scrollbars=yes,height="+screen.availHeight+",width="+screen.availWidth+",left=0,top=0,resizable=yes,toolbar=no,location=no,status=no");
If you need to open any popups, there are likely better ways to meet your requirements. If you are opening several popups, then your design needs a thorough review (consider your workflow and whether a tabbed interface is a better option).
The usual strategy is to save a reference to each window, then check if it's still open and available for re-use later, e.g.
var popWin;
function openWindow(url) {
var windowName = '...';
var features = '...';
if (!popWin || popWin.closed) {
popWin = window.open(url, windowName, features);
} else {
popWin.location.href = url;
}
}
If you want to have multiple windows open, then you will need a strategy for tracking which one you want to load a particular resource into.
You may find the HTML5 window (creating and navigating contexts by name) and MDN window.open documentation useful.

Javascript: Check for duplicate opened window

Is it possible to check if same window is already opened?
For example i have opened a window via javascript.
Can i check if that's opened on another page via javascript?
Just want to focus on page if it's been opened already to avoid duplicate windows.
Thanks ;)
Look at window.open() method. You must specify the name of the window as the second parameter. If there already is a window with that name, then the new URL will be opened in the already existing window, see http://www.w3schools.com/jsref/met_win_open.asp
If you really want to check, if the window is opened by your own scripts, then you have to keep a reference to the opened window in a global variable or the likes and create it with
var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow");
You can also encapsulate this behavior in a method:
var myOpenWindow = function(URL) {
var myOpenedWindow = myOpenedWindow || window.open(URL, "MyNewWindow");
myOpenedWindow.location.href= URL;
myOpenedWindow.focus();
}
And call that function with myOpenWindow('http://www.example.com/');
If you have parent--child window then here is a solution that will allow you to check to see if a child window is open from the parent that launched it. This will bring a
focus to the child window without reloading its data:
<script type="text/javascript">
var popWin;
function popPage(url)
{
if (popWin &! popWin.closed && popWin.focus){
popWin.focus();
} else {
popWin = window.open(url,'','width=800,height=600');
}
}
</script>
<a href="http://www.xzy.com"
onclick="popPage(this.href);return false;">link</a>
one more thing ::--- If the user refreshes the parent window, it may loses all its
references to any child windows it may have had open.
Hope this helps and let me know the output.
This will help if you want to open a url from a link
var Win=null;
function newTab(url){
//var Win; // this will hold our opened window
// first check to see if the window already exists
if (Win != null) {
// the window has already been created, but did the user close it?
// if so, then reopen it. Otherwise make it the active window.
if (!Win.closed) {
Win.close();
// return winObj;
}
// otherwise fall through to the code below to re-open the window
}
// if we get here, then the window hasn't been created yet, or it
// was closed by the user.
Win = window.open(url);
return Win;
}
newTab('index.html');

window.close(); not working when page changed or refreshed

I have this little function to open/close a popup player:
function popuponclick(popup)
{
my_window = window.open("folder/player-itself.htm", popup, "width=350,height=150");
}
function closepopup()
{
my_window.close();
}
I call the functions from HTML anchors that are on each page of the site (idea is to have the player stopped/started whenever you want)...now...
it works well until i change the page, or refresh the existing one - and from then the window can't be closed anymore. Any idea where i'm wrong? Tested in FF and IE8, same behavior.
Thanks for your help.
When you reload the original window (or tab), everything about the old one is gone, blasted into the digital void, never to be seen or heard from again. The bits literally disintegrate into nothingness.
Thus, the "my_window" reference you so lovingly saved when the second window was opened is gone for good, and the "my_window" variable in the newly-loaded window contains nothing. It's name is but a mockery of the variable in the now-dead page.
The only way to deal with this situation is for the popup window to periodically check back via "window.opener" to see if its parent page has been rudely replaced by some interloper. If that happens (and the new page is from the same domain), then the popup page can restore the reference to itself in the new page's "my_window" variable.
edit — OK here's a sample. You'd put something like this in the popup page, not the launching pages:
<script>
var checkParent = setInterval(function() {
try {
if (window.opener && ('my_window' in window.opener))
window.opener.my_window = window;
}
catch (_) {
// clear the timer, since we probably won't be able to fix it now
clearInterval(checkParent);
}
}, 100);
</script>
That's probably pretty close.

Find window previously opened by window.open

We've got the following situation, running from a single domain:
Page A uses window.open() to open a named window (a popup player). window.open() gives page A a reference to the window.
User now reloads page A. The reference to the named window is lost. Using window.open() to "find" the window has the unfortunate side effect of reloading it (undesirable). Is there any other way to get a reference to this window?
Try this:
var playerUrl = 'http://my.player...';
var popupPlayer= window.open('', 'popupPlayer', 'width=150,height=100') ;
if(popupPlayer.location.href == 'about:blank' ){
popupPlayer.location = playerUrl ;
}
popupPlayer.focus();
It will open a blank window with a unique name. Since the url is blank, the content of the window will not be reloaded.
AFAIK, no there isn't..
A kind-of-dirty-but-i-guess-it-will-work hack would be to periodically reset the reference on the parent window from within the popup using window.opener, with something like this code:
setInterval(function() {
if(window.opener) {
window.opener.document.myPopupWindow = window
}
}, 100)
In the parent window, you'll be able to access document.myPopupWindow, even after a reload (well, 100ms after the reload). This should work cross browser.
Actually what you did is destroy the parent (page A) of the created window (Popup), so it has no more reference to the original parent therefore you can't get a direct reference.
The only solution I can think of is using a browser that offers you added javascript capability to cycle through active windows (tabs) and find one that has a special property (ie: your reloaded page A) that gets recognized by the popup.
Unfortunately I guess only firefox has some added capability or extension that gives you this flexibility. (it is also a security risk though)
This should work. Add this code in the popup:
function updateOpener() {
if (window.opener)
window.opener.document.myPopupWindow = window;
else
setTimeout(updateOpener, 100);
}
updateOpener();
And this in onload of the parent window. To make sure myPopupWindow have been set wait 100 ms before accessing it.
setTimeout(function() {
if (document.myPopupWindow)
document.myPopupWindow.focus();
}, 100);
If all the windows share a common Url origin you can register a ServiceWorker and then access all windows from the ServiceWorker: https://developer.mozilla.org/en-US/docs/Web/API/Clients
AFAIK You won't be able to pass a reference to other windows from WorkerService to your window but you can establish communications with the ServiceWorker via
https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage
It Might help someone, If you opened an child tab and after refreshing the parent tab, you still want to focus on that child tab instead of opening new child tab: -
const chatPopup = window.open('', 'chatPopup');
if (chatPopup.location.href === 'about:blank' || !chatPopup.location.href.includes('/chat')) {
this.openNewWindow = window.open('/chat', 'chatPopup');}

Categories