Persistent Data with Javascript - javascript

I have an application that has a "parent" window. In the parent window there are menu items, like the following (using PHP here):
// sample link
echo "<li><a href=\"#\" onclick=openurl('covershift.php');>Shift Coverage</a></\
li>";
// logout link
echo "<li><a href=\"#\" onclick=openurl('logout');>Logout</a></li>";
Each link opens the appropriate page in a different "child" window. When the parent closes all of the child windows must close. I have implemented this functionality with Javascript, here is the function:
var childWindow = new Array();
var windowCount = 0;
function openurl(url)
{
if(url != 'logout') {
childWindow[windowCount]=window.open(url,'_blank','height=600,width=800,scr\
ollbars=1');
windowCount++;
if (window.focus) {
childWindow.focus();
}
} else {
var iCount;
for (iCount=0; iCount < windowCount; iCount++) {
if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
childWindow[iCount].close();
}
}
window.location='logout.php';
}
}
Here is my problem, when a user reloads the parent window and then clicks logout, the child windows remain open. This makes sense as the childWindow array is lost when the parent reloads.
How can I make the childWindow array persistent through a reload?
Thanks!

I don't think you can make a JavaScript object persist through a window load. Instead, could you make an unload event handler that closes your pages?
window.onunload = myCloseFunction;
function myCloseFunction()
{
// Just copying your code...
var iCount;
for (iCount=0; iCount < windowCount; iCount++) {
if ((childWindow[iCount] != null) && !(childWindow[iCount].closed)) {
childWindow[iCount].close();
}
}
}
Another option might be to have the child windows poll for the existence of the parent.
In the child window:
// Checks every 1 second for valid window.opener
var parentChecker = setInterval(function(){
if(!opener){
// Is this good practice? I don't know!
clearInterval(parentChecker);
window.close();
}
}, 1000);

You can save that array in the LocalStorage or in a cookie

Related

Click link to ask save changes and refresh on another page

I have two pages: main page and child page. on the main page, I have a link will direct user to the child page. And in the main page, there's a listener to check if child window closed, it will refresh main page automatically.
in the main page, the link is:
<asp:HyperLink ID="hlchild" runat="server" NavigateUrl="javascript:void(openchild('../test/child','child'));">child page</asp:HyperLink>
and below is the function for openchild:
var childWindow;
var timer;
function openchild(vurl) {
childWindow = window.open(vurl, 'child');
clearInterval(timer);
timer = setInterval(checkChild, 1000);
}
function checkChild() {
if (childWindow.closed) {
childWindow = null;
clearInterval(timer);
__doPostBack('hdPB_Refreshpage', '');
}
}
Now, I want to add a function: whenever I click the child link from main page, checking whether the child page is opened. if yes, then ask user whether save changes on child page before refresh the child page. If user click yes, then it will trigger the save changes function on child, otherwise just refresh the child page to open.
below is the button on child page for saving changes:
<button type="submit" id="subSave" name="Save" value="Save" class="btn btn-outline-dark">
<i class="far fa-save"></i> Save
</button>
You should use cross window communications that js expose, like post messages, more you can read here.
Just add event listener on the child window with the name of message that you will sent, and from parent window send that message.
var childWindow = window.open(/* details */);
childWindow.postMessage("hello world", "http://example.com");
window.addEventListener("message", (event) => {
if (event.origin !== "http://example.com")
return;
// event.source is childWindow
// event.data
}, false);
Just a update for my solution. So finally I just call the function from child window.
In the main page:
var childWindow;
var timer;
function openchild(vurl) {
//check if the child window is existing, then popup for asking whether save changes
if (childWindow != null) {
if (confirm('Do you want to save changes before proceeding?')) {
//save changes on that page
childWindow.ProcessParentSaveChanges();
childWindow.focus();
return;
}
}
childWindow = window.open(vurl, 'child');
clearInterval(timer);
timer = setInterval(checkChild, 1000);
}
function checkChild() {
if (childWindow.closed) {
childWindow = null;
clearInterval(timer);
__doPostBack('hdPB_Refreshpage', '');
}
}
in child page:
function ProcessParentSaveChanges() {
var btn = document.getElementById("subSave");
btn.form.submit();
}

How to cascade JavaScript unloads to child windows?

I want to unload dependent pop-ups when the main window closes.
Main window:
var dependentWindows = [];
function closeDependents(){
dependentWindows.forEach(function(dependent) {
dependent.close();
})
dependentWindows = [];
}
function addDependent(dependent){
if(dependentWindows.indexOf(dependent) < 0) {
dependentWindows.push(dependent);}
}
function removeDependent(dependent){
var position = dependentWindows.indexOf(dependent);
if(position > 0) {
dependentWindows.splice(position,1);}
}
Event.observe(window,"unload",closeDependents);
dependent pop-up window:
function addDependent(dependent){
window.opener.addDependent(dependent);
}
function removeDependent(dependent){
window.opener.removeDependent(dependent);
}
Event.observe(window, "load", (function() {addDependent(window);});
Event.observe(window, "unload", (function() {removeDependent(window);});
None of this is firing....?
I want to unload dependent pop-ups when the main window closes
A simple and easiest solution could be to include a small script in each of your child windows, which will periodically poll to see if its opener window is still alive.
Something like this:
setInterval(checkIfOrphaned, 2000);
function checkIfOrphaned() {
if (!window.opener || (window.opener == 'null') || (window.opener.closed)) {
window.close();
}
}

Issue with "Handleonclose" functionality on jsp page

I have a jsp file which calls another jsp file opening it as a showmodal dialog window.
Say file1.jsp calls file2.jsp through file1.js.
File1.jsp-->File1.js (respective js files)
File2.jsp-->File2.js(respective js files)
Now to handleonclose in File2.jsp I added a function in File2.js.
When I hit close window but choose option as cancel, instead of just showing the old window.
It shows a modal window ontop of the existing modal window. Why is this happening. Am I missing something obvious.
What i expect to happen: When I choose Close but click cancel, nothing should happen.
File2.js function:
function handleOnClose() {
var resultsDoc = document.frames('searchBuffer').document;
if (event.clientY < 0) {
var bool = confirm('Are you sure you want to close the window ?');
if (!bool) { //Issue occurs here
window.showModalDialog("File2.jsp", "", "dialogWidth:1000px;dialogHeight:650px");
}
else {
resultsDoc.all('searchResults').innerText = '';
document.someSearch.submit();
}
}
window.returnValue = 'Discard';
}
Modified File2.js function:
function handleOnClose() {
var resultsDoc = document.frames('searchBuffer').document;
if (event.clientY < 0) {
var bool = confirm('Are you sure you want to close the window ?');
if (!bool) { //Issue occurs here
//*******removed the showmodal dialog window call
window.returnValue = 'Sorry';
}
else {
resultsDoc.all('searchResults').innerText = '';
document.someSearch.submit();
window.returnValue = 'Discard';
}
}
}
On the calling js (file1.js) I check if return value is "Discard" if so I refresh the page.
Otherwise I call the showmodal window again. My result is stored in the buffer so retrieval isn't a problem. Works like a charm

javascript html5 history, variable initialization and popState

main question
Is there a javascript way to identify if we are accessing a page for the first time or it is a cause of a back?
My problem
I'm implementing html5 navigation in my ajax driven webpage.
On the main script, I initialize a variable with some values.
<script>
var awnsers=[];
process(awnsers);
<script>
Process(awnsers) will update the view according to the given awnsers, using ajax.
In the funciton that calls ajax, and replaces the view, I store the history
history.pushState(state, "", "");
I defined the popstate also, where I restore the view according to the back. Moreover, I modify the global variable awnsers for the old value.
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
}
}
Navigation (back and forth) goes corectly except when I go to an external page, and press back (arrving to my page again).
As we are accessing the page, first, the main script is called,the valiable awnsers is updated, and the ajax starts. Meanwile, the pop state event is called, and updates the view. After that the main ajax ends, and updates the view according to empty values.
So I need the code:
<script>
var awnsers=[];
process(awnsers);
<script>
only be called when the user enters the page but NOT when it is a back. Any way to do this?
THanks!
Possible solution
After the first awnser I have thought of a possible solution. Tested and works, whoever, I don't know if there is any cleaner solution. I add the changes that I've done.
First I add:
$(function() {
justLoaded=true;
});
then I modify the popState function, so that is in charge to initialize the variables
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
} else if(justLoaded){
awnsers=[];
process(awnsers);
}
justLoaded=false;
}
Thats all.
what about using a global variable?
var hasLoaded = false;
// this function can be called by dom ready or window load
function onPageLoad() {
hasLoaded = true;
}
// this function is called when you user presses browser back button and they are still on your page
function onBack() {
if (hasLoaded) {
// came by back button and page was loaded
}
else {
// page wasn't loaded. this is first visit of the page
}
}
Use cookie to store the current state.
yeah! This is what I have:
var popped = (($.browser.msie && parseInt($.browser.version, 10) < 9) ? 'state' in window.history : window.history.hasOwnProperty('state')), initialURL = location.href;
$(window).on('popstate', function (event) {
var initialPop = !popped && location.href === initialURL, state;
popped = true;
if (initialPop) { return; }
state = event.originalEvent.state;
if (state && state.reset) {
if (history.state === state) {
$.ajax({url: state.loc,
success: function (response) {
$(".fragment").fadeOut(100, function () {
$(".fragment").html($(".fragment", response).html()).fadeIn(100);
);
document.title = response.match(/<title>(.*)<\/title>/)[1];
}
});
} else { history.go(0); }
else {window.location = window.location.href; }
});
And:
$.ajax({url:link,
success: function (response) {
var replace = args.replace.split(",");
$.each(replace, function (i) {
replace[i] += ($(replace[i]).find("#video-content").length > 0) ? " #video-content" : "";
var selector = ".fragment "+replace[i];
$(selector).fadeOut(100, function () {
$(selector).html($(selector,response).html()).fadeIn(100, function () {
if (base.children("span[data-video]")[0]) {
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$("#theVideo").html("");
_.videoPlayer();
} else {
_.player.cueVideoById(base.children("span[data-video]").attr("data-video"));
}
}
});
});
});
document.title = response.match(/<title>(.*)<\/title>/)[1];
window.history.ready = true;
if (history && history.pushState) { history.pushState({reset:true, loc:link}, null, link); }
}
});

javascript open parent window

The following is in the NewForm.aspx which gets executed from a parent page (surveys/lists/testsurvey/allitems.aspx). The javascript works and open google. However, it opens the google in the pop up window (newform.aspx) but i need to close the popup window and show google.com on the parent window (or whatever the parent window link is)
<script type="text/javascript">
function redirect()
{
var inputcCtrls = document.getElementsByTagName("input");
for(m=0; m<inputcCtrls.length; m++)
{
if(inputcCtrls[m].type == 'button' && inputcCtrls[m].value == 'Finish')
{
var funcOnClick = inputcCtrls[m].onclick;
inputcCtrls[m].onclick = function () { window.location = "http://www.google.com/" }; }
}
}
redirect();
</script>
Use the opener property to find the window that opened the current window:
window.opener.location = "http://www.google.com/";
window.close();

Categories

Resources