Navigating Between HTML Windows - javascript

and thanks for taking a look at this seemingly simple question.
The scenario is as follows: I have a website Homepage named 'welcome.html'. From here users can select from a list of URLs and on clicking on the URL a simple Javascript function is called which opens a new Window.
Once the user has finished in the newly opened Window I want them to click on a button which calls a Javascript function to return them to the Homepage. It seems so simple.
However, if the Homepage Window is still open I want to return to this and not open another new Window displaying the Homepage. If the Homepage Window has been closed then I want a new Window to open displaying the Homepage.
I would be very grateful for some guidance here as I can't seem to get it to work.
Regards
Chris

As others have said, it is not the greatest design. However, I've run into scenarios like this in the past, where the business logic stipulates that a new window must be opened and there is no ability to change that.
As Pointy said, the biggest thing is just to keep track of the windows opened, and if you need some further help, perhaps this may help:
http://www.quirksmode.org/js/popup.html
But if possible, I would consider a different design (ask here if you need help implementing it!)

and thank you everyone who went to the trouble of sharing their thoughts.
I solved the problem in the following way:
When navigating from the Homepage to the new Window the following Javascript is used to open a new Window:
function popupFull(url)
// For explanation of this code see: http://www.quirksmode.org/js/popup.html
// Note: If fullscreen = 1 you can't see the menubar, toolbar, status etc.
// It is advisable to have no spaces around the commas in the parameters.
{
//alert("Opening: " + url)
// Prepare the parameter string
params = 'width='+screen.width;
params += ',height='+screen.height;
params += ',top=0,left=0';
params += ',fullscreen=0';
params += ',menubar=0';
params += ',toolbar=0';
params += ',directories=0';
params += ',status=0';
params += ',scrollbars=0';
params += ',resizable=1';
// Open a new window.
newWin=window.open(url, "fullWindow", params);
// If the current Window is in focus, switch focus to the new Window.
if (window.focus)
{
newWin.focus()
}
// Return the new Window object reference.
return newWin;
}
So the new Window can be opened and I have left the Homepage Window open but out of focus behind the new Window.
In the new Window there is a 'Menu' button. Clicking on this calls the following Javascript function:
function openMenu(winURL, winName, winFeatures)
{
// Create a reference of the Window which opened this Window. This should be
// the Main Menu Window.
var winObj=window.opener;
var menuOuterWidth = 1080;
var menuOuterHeight = 896;
var menuInnerWidth = 1068;
var menuInnerHeight = 767;
var menuX = (screen.width - menuOuterWidth) / 2;
var menuY = (screen.height - menuOuterHeight) / 2;
// Prepare the parameter string for re-opening the Menu
params = 'width='+menuInnerWidth;
params += ',height='+menuInnerHeight;
params += ',top='+menuY+',left='+menuX;
params += ',fullscreen=0';
params += ',menubar=1';
params += ',toolbar=1';
params += ',status=1';
params += ',scrollbars=1';
params += ',location=1';
params += ',resizable=1';
try
{
// Check to see if the window reference already exists.
if (winObj)
{
// Check to see if the Menu window is closed.
if (winObj.closed)
{
// The Menu window is closed.
// Open the Menu Window.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
else
{
// The Menu Window has not been closed. Set the Window's size and position.
// Note: When resizing the outerWidth/outerHeight value has to be passed.
winObj.window.resizeTo(menuOuterWidth, menuOuterHeight);
winObj.window.moveTo(menuX, menuY);
// Bring it into focus (bring to front).
winObj.focus();
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
else
{
// The winObj object does not exist. Open the Menu.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
//alert(txt);
// When IE6 tries to obtain the winObj.closed property, when the window is closed, it can cause
// an error "Permission Denied". This error is caught here. Open the Menu.
// Open the Menu Window.
winObj = window.open(winURL, winName, params);
// Close this Course Window.
window.close();
// Return the Menu Window object reference should the caller want it.
return winObj;
}
}
The comments should explain everything. The key is to get a reference to the Homepage Window where we started. (var winObj=window.opener;).
What caused me such a headache was that if I opened the new Window (using IE6), switched back to the Homepage and closed the Homepage Window, and then in the new Window clicked on the 'Menu' button nothing happened! I tried everything and then, after a cup of tea, realised that I would never write code in any application I was developing without any form of error capture. I added a Try, Catch statement and reported the error in an 'alert'. I got a 'Permission Denied' error.
After a lot of reading I figured I couldn't eliminate the error I would simply handle the error as elegantly as I could. This resulted in the code above.
It works a treat and I hope this helps someone.

Related

postMessage once the window loads successfully

I am trying to implement following feature
User opens up a page 1 on which there is a button. On clicking that button another window opens up but before that program checks whether the window is already open or not if it is already open than re-open the existing window or else open the new window.
While opening a window , I am passing some data to newly / existing open window using postMessage.
Now, the problem is when I am opening a window ( if it is NOT already open) then sometimes window is not able to receive the message sent by postMessage` hence I have used the setTimeout in following code.
However, this is not a reliable solution so I need a way where in newly open window receive the message each time.
Following is the code of service worker
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url === urlToOpen) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
// if window is already open then just focus on window
matchingClient.focus();
// post the message
channel.postMessage({action: event.action,information:event.notification.data ? event.notification.data.info : ""});
} else {
//if window is not open yet, then open a new window
clients.openWindow(urlToOpen);
//have used setTimeout because opening a window may take time , however this is just a workaround
setTimeout(function(){
console.log("Delayed");
//post the message
channel.postMessage({action: event.action,information:event.notification.data ? event.notification.data.info : ""});
},4000);
}
});

Access a new window - cypress.io

The question is as simple as that. In Cypress, how can I access a new window that opens up when running the test.
Steps to recreate :
Run the test. After some action, new window pops up (the url is dynamic in nature).
Fill in the fields in the new window, and click a few buttons.
After required actions are completed in the new Window, close the new window and move back to the main window.
Continue execution with the main window.
Point of interest: the focus should be
main window -> new window -> main window
I have read few things that relate to use of iframe and confirmation box, but here its none of those. Relates to accessing a whole new window. Something like Window Handlers in Selenium. Unfortunately could not find anything related to it.
Accessing new windows via Cypress is intentionally not supported.
However, there are many ways this functionality can be tested in Cypress now. You can split up your tests into separate pieces and still have confidence that your application is covered.
Write a test to check that when performing the action in your app, the window.open event is called by using cy.spy() to listen for a window.open event.
cy.visit('http://localhost:3000', {
onBeforeLoad(win) {
cy.stub(win, 'open')
}
})
// Do the action in your app like cy.get('.open-window-btn').click()
cy.window().its('open').should('be.called')
In a new test, use cy.visit() to go to the url that would have opened in the new window, fill in the fields and click the buttons like you would in a Cypress test.
cy.visit('http://localhost:3000/new-window')
// Do the actions you want to test in the new window
Fully working test example can be found here.
I am not cypress expert, just started using it few days ago, but I figured out this kind solution for stateful application with dynamic link:
// Get window object
cy.window().then((win) => {
// Replace window.open(url, target)-function with our own arrow function
cy.stub(win, 'open', url =>
{
// change window location to be same as the popup url
win.location.href = Cypress.config().baseUrl + url;
}).as("popup") // alias it with popup, so we can wait refer it with #popup
})
// Click button which triggers javascript's window.open() call
cy.get("#buttonWhichOpensPopupWithDynamicUrl").click()
// Make sure that it triggered window.open function call
cy.get("#popup").should("be.called")
// Now we can continue integration testing for the new "popup tab" inside the same tab
Is there any better way to do this?
// We can remove the offending attribute - target='_blank'
// that would normally open content in a new tab.
cy.get('#users').invoke('removeAttr', 'target').click()
// after clicking the <a> we are now navigated to the
// new page and we can assert that the url is correct
cy.url().should('include', 'users.html')
Cypress - tab handling anchor links
I was able to achieve the same requirement via the following:
let newUrl = '';
cy.window().then((win) => {
cy.stub(win, 'open').as('windowOpen').callsFake(url => {
newUrl = url;
});
})
cy.get('.open-window-btn').click()
cy.get('#windowOpen').should('be.called');
cy.visit(newUrl)
Here's a solution i'm using on my project based on "Cypress using child window"
Cypress Window Helpers (aka. Cypress Tab Helpers)
They're really popup-windows or child-windows, but i call them tabs for api brevity
cy.openTab(url, opts)
cy.tabVisit(url, window_name)
cy.switchToTab(tab_name)
cy.closeTab(index_or_name) - pass nothing to close active tab
cy.closeAllTabs() - except main root window
I was recently faced with this issue as well - url for the new tab is dynamic, so I don't know what it is. After much searching, some trial and error, and input from co-workers, resolved by doing the following:
// AFTER cy.visit()
cy.window().then((win) => {
cy.spy(win, 'open').as('windowOpen'); // 'spy' vs 'stub' lets the new tab still open if you are visually watching it
});
// perform action here [for me it was a button being clicked that eventually ended in a window.open]
// verify the window opened
// verify the first parameter is a string (this is the dynamic url) and the second is _blank (opens a new window)
cy.get('#windowOpen').should('be.calledWith', Cypress.sinon.match.string, '_blank');
this is how you can handle tabs in same window..
use this code snippet
cy.xpath("//a[#href='http://www.selenium.dev']").invoke('removeAttr','target').click();

titanium, save the state of last viewed window

I am wondering if there is a function for saving the last viewed window when a user quits the application, so when they go into the app again, it goes to the last viewed page, instead of restarting. I have looked at Ti.App.Properties but haven't really found what I was looking for. Can anyone point me in the right direction, or if this is even possible.
Thanks
Ti.App.Properties is the way to go.
If you are just looking to save which window the user was on, simply save the current window that the user is on every time the window changes.
If you want to save the current state, as your title suggests, you will also want to create a javascript object that holds all the data on the page, do JSON.stringify(object) and then save that string in a property as well.
There is an example of code you can use to manage the state of the last opened window :
// Windows types
var TYPE_HOME = 'HomeWindow',
TYPE_BLUE = 'BlueWindow';
// Properties' keys
var PROPERTY_LAST_OPENED_WIN = 'lastOpenedWindow';
// open the last opened window
var win = openLastWindow();
// Uncomment to open the blue window
// Then, comment and reopen the app => the blue window will be opened
//createAndOpenBlueWindow();
// Save the last window configuration
function setLastWindow(params) {
Ti.App.Properties.setString(PROPERTY_LAST_OPENED_WIN, JSON.stringify(params));
}
// Create and open the last window opened
// (the function you have to call when you re-open the app)
function openLastWindow() {
var params = JSON.parse(Ti.App.Properties.getString(PROPERTY_LAST_OPENED_WIN, '{}'));
switch (params.type) {
case TYPE_HOME: return createAndOpenHomeWindow();
case TYPE_BLUE: return createAndOpenBlueWindow();
default : return createAndOpenHomeWindow();
}
}
// Create a window with the given params AND
// save this window as last opened window
function createAndOpenWindow(params) {
var win = Ti.UI.createWindow(params);
setLastWindow(params);
win.open();
return win;
}
// Create windows of type "HomeWindow"
function createAndOpenHomeWindow() {
return createAndOpenWindow({type:TYPE_HOME, backgroundColor:'#FF0000'});
}
// Create windows of type "BlueWindow"
function createAndOpenBlueWindow() {
return createAndOpenWindow({type:TYPE_BLUE, backgroundColor:'#0000FF'});
}
This code creates and opens the last window opened thanks to the openLastWindow function.
The first time you open the app, the Home one will be opened (the red).
By uncommenting this line :
//createAndOpenBlueWIndow();
you will open the BlueWindow the next time you run the app.
Then, re-comment this line. The blue window will be opened (since it is the last opened).
Hope this helps !

Check if window is already open window.open

I have a html page. In the body of the page I am calling onload event which calls javascript function to open a pop up window. here is the code:
var newWindow = null;
function launchApplication()
{
if ((newWindow == null) || (newWindow.closed))
{
newWindow = window.open('abc.html','','height=960px,width=940px');
}
}
when I move to another page, and come back to that page again, popup reopens, although it is already opened. Please guide me to proper direction so that if pop up is already open then it should not open again. I tried document.referred but it requires the site online, currently I am working offline.
newWindow = window.open('abc.html','com_MyDomain_myWindowForThisPurpose','height=960px,width=940px');
Give the window a name. Basing the name on your domain like this, prevents the chances of you picking a name someone else happened to choose.
Never make up a name that begins with _, those are reserved for special names the browser treats differently (same as with the "target" attribute of anchor elements).
Note that if the window of that name was opened with different options (e.g. different height), then it'll keep those options. The options here will only take effect if there is no window of that name, so you do create a new one.
Edit:
Note that the "name" is of the window, not of the content. It doesn't affect the title (newWindow.document.title will affect that, as of course will code in abc.html). It does affect other attempts to do stuff across windows. Hence another window.open with the same name will reuse this window. Also a link like clicky! will re-use it. Normal caveats about browsers resisting window-opening in various scenarios (popup-blocking) apply.
To open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '');
if(winref.location.href === 'about:blank'){
winref.location.href = 'http://example.com';
}
or in function format
function openOnce(url, target){
// open a blank "target" window
// or get the reference to the existing "target" window
var winref = window.open('', target, '');
// if the "target" window was just opened, change its url
if(winref.location.href === 'about:blank'){
winref.location.href = url;
}
return winref;
}
openOnce('http://example.com', 'MyWindowName');
You can check if the window is open or closed by re-assigning a reference to it when it closes. Example:
var newWindow;
var openWindow = function(){
newWindow = newWindow || window.open('newpage.html');
newWindow.focus();
newWindow.onbeforeunload = function(){
newWindow = null;
};
};
Use the "closed" property: if a window has been closed its closed property will be true.
https://developer.mozilla.org/en-US/docs/Web/API/Window/closed
When you move on another page (on the same domain), you can re-set the window.open variable with popup page like this :
https://jsfiddle.net/u5w9v4gf/
Step to try :
Click on Run (on jsfiddle editor).
Click on Try me (on preview).
Click on Run to move on another page, the variable will be re-set.
Code :
window.currentChild = false;
$("#tryme").click(function() {
if (currentChild) currentChild.close();
const child = window.open("about:blank", "lmao", 'width=250,height=300');
currentChild = child;
//Scrope script in child windows
child.frames.eval(`
setInterval(function () {
if (!window.opener.currentChild)
window.opener.currentChild = window;
}, 500);
`);
});
setInterval(function() {
console.log(currentChild)
if (!currentChild || (currentChild && currentChild.closed))
$("p").text("No popup/child. :(")
else
$("p").text("Child detected !")
}, 500);

window.open and searchpopop

We are use window.open for open popup. But then we want find it and close. Unfortunately we can`t save this popup handle to variable.
P.S. How get list of all windows?
This should work:
var wh = window.open(..)
wh is the handle to the popup window.
If you have control over the page that loads the script, you could do something like this. Warning: this is a really scary and generally bad thing to do:
<script>
var windowHandles = {};
(function() {
var realOpen = window.open;
window.open = function(url, name, features) {
windowHandles[name] = realOpen(url, name, features);
};
})();
</script>
That will build an object (windowHandles) in which the handles for each opened window will be saved.
Put that script in your page before the script that opens the other window is loaded.
I found not perfect solution, but it work.
win = window.open(null, 'Window1');
This code search search window with this name and return handler, but if window is closed it open empty popup.
I Think this is temporary solution
I don't like this solution. Fixing the script to give you a handle would be a better bet.
<button onclick="go()">Go</button>
<button onclick="stop()">Stop</button>
<script type="text/javascript">
function go() {
// Existing function. It opens a window with a name.
window.open('http://google.com', 'test', 'width=300,height=300');
}
var foo;
function stop() {
// Open a new window with the same name. It replaces the existing window.
// Since it opens a local document, the Same Origin Policy does not apply.
// ... and we can capture its return value to grab a handle on an existing
// window
foo = window.open('black-local-page.html', 'test', 'width=300,height=300');
// Give the local page time to load
setTimeout(continue_stopping, 500);
}
function continue_stopping() {
// Call window.open() on the window
foo.close();
}
</script>

Categories

Resources