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();
}
Related
I'm trying to refresh a page and then run a function once the refresh has been completed. However the code I have now, runs the function and then it only refreshes it, meaning I lose what the function did. Is there a way to solve this?
My code
function reloadP(){
document.location.reload();
myFunction();
}
<button onclick: "reloadP()">Click</button>
You need to call myFunction() when the page is loaded.
window.onload = myFunction;
If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO
function myFunction() {
document.getElementById("welcome").textContent = "Welcome back!";
}
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
myFunction();
}
}
function reloadP() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
DEMO: https://jsfiddle.net/barmar/5sL3hd74/
Adding to #Barmar answer... In case you'd like to use session storage only when a button in the page is clicked and not when reloading with the browser button, you can use sessionStorage.clear() or sessionStorage.removeItem() once you've executed the function after loading the window.
So, let's say we have:
let restart = sessionStorage.getItem("restart")
Set restart boolean to true as a session storage and reload:
resetBtn.addEventListener("click", () => {
sessionStorage.setItem("restart", "true")
location.reload()
})
Once the window is reloaded we can execute the following function:
window.onload = () => {
if(restart){
// Do something
sessionStorage.clear() // This cleans all the session storage
// If you want to remove ONLY the item from the storage use:
// sessionStorage.removeItem("restart")
}
};
So, if now the user reloads the page with the browser button it will reload with the session storage cleaned. Meaning, no functions will be executed after window load.
In my case i used Barmar's solution. I have a modal popup form, i want to submit the form then automatically refresh the page and finally success message on reloaded page.
var form = document.getElementById('EditUserInfosForm')
form.addEventListener('submit', function () {
sessionStorage.setItem("reloading", "true");
document.location.reload();
})
window.onload = function () {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
$('#success-message-modal').modal('show')
}
}
Probably simplest approach.
HTML Button
Reload button (credits):
<!-- index.html -->
<button onClick="window.location.reload();">Refresh Page</button>
JS Code
Run your code after reload:
// index.js
window.addEventListener("load", (event) => {
YourFunction(); // already declared somewhere else
});
You may not use event variable at all.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#examples
I am using shopify's built in customer create, login, reset form submissions which on submit, forces the page to refresh. My intention is to show a message that shows after the page has been refreshed via a button click function. This is what i have so far; The message shows until that page refreshes and then the active class is removed as you would expect.
$(document).ready(function () {
class Alert {
constructor() {
this.customerAlert = document.createElement('div');
}
init(){
this.customerAlert.classList.add('customer-alert');
document.querySelector('body').append(this.customerAlert);
}
show(message){
this.customerAlert.textContent = message;
this.customerAlert.classList.add('active');
setTimeout(() => {
this.customerAlert.classList.remove('active');
}, 8000);
}
}
//create snackbar and initiate
const alertMessage = new Alert();
alertMessage.init();
const createAccountButton = document.querySelector('input.account-trigger');
createAccountButton.addEventListener('click', () => {
alertMessage.show('Your account in now under review');
});
});
Set a boolean variable in session storage just prior to the submit to represent the two states, and then read it in after the refresh.
Something like this:
function HandleFlag(){
var F=sessionStorage.getItem('Flag');
if(F=='1'){
// display your message box here
sessionStorage.setItem('Flag','0');
} else {
// the state is "0" so toggle it just before submitting
sessionStorage.setItem('Flag','1');
}
}
I hope you get my drift.
How can I close modal dialog(s) from main page after some time, or when session expires, using JavaScript or jQuery?
Dialog is opened using the following code :
var result = window.showModalDialog("test.aspx" ... );
Dialog must be closed when counter expires like this:
function Discount() {
leftSeconds = leftSeconds - 1;
try { document.getElementById('tbLeft').value = leftSeconds; } catch (ex) { }
if (leftSeconds <= 5) {
clearTimeout(t);
// code for closing modal dialog(s)
} else {
t = setTimeout("Discount()", 1000);
}
}
Modal dialog can be closed from himself, but it's not solution in my case.
While the modal dialog is open, javascript execution on the main page is stopped, because it is waiting for a return value (even though you may not want to return one, or do anything with what it returns).
You can check this with this little example. When you click the button, the page opens, and the timer stops updating. When you close the page, execution is resumed:
<!DOCTYPE html>
<html>
<head>
<script>
var t = 0;
function count() {
document.getElementById('div').innerHTML = ++t;
}
var timer = setInterval(count, 1000);
</script>
</head>
<body>
<div id='div'></div>
<button onclick="window.showModalDialog('http://www.google.es');">Open window</button>
</body>
</html>
So, if you want to close the window automatically, you need to do it from the new document itself. My advice? Implement your timer in the window.load event of your modal page, so it can close itself after the desired time.
window.onload = function() {
setTimeout(function() { window.close(); }, 60000); //close window after 1 minute.
};
I want that when a user clicks on any external link (identified by either particular id or class) on my site then he should get a popup with a counter of 10 seconds, after 10 seconds the popup should close and the user should be able to access the external URL. How can this be done? I'm able to show a warning like below but I don't know how to add timeout to it, also this is a confirm box, not a popup where I can add some div and more stuff for user to see until the counter stops.
$(document).ready(function(){
var root = new RegExp(location.host);
$('a').each(function(){
if(root.test($(this).attr('href'))){
$(this).addClass('local');
}
else{
// a link that does not contain the current host
var url = $(this).attr('href');
if(url.length > 1)
{
$(this).addClass('external');
}
}
});
$('a.external').live('click', function(e){
e.preventDefault();
var answer = confirm("You are about to leave the website and view the content of an external website. We cannot be held responsible for the content of external websites.");
if (answer){
window.location = $(this).attr('href');
}
});
});
PS: Is there any free plugin for this?
I've put together a little demo to help you out. First thing to be aware of is your going to need to make use of the setTimeout function in JavaScript. Secondly, the confirmation boxes and alert windows will not give you the flexibility you need. So here's my HTML first I show a simple link and then created a popup div that will be hidden from the users view.
<a href='http://www.google.com'>Google</a>
<div id='popUp' style='display:none; border:1px solid black;'>
<span>You will be redirected in</span>
<span class='counter'>10</span>
<span>Seconds</span>
<button class='cancel'>Cancel</button>
</div>
Next I created an object that controls how the popup is displayed, and related events are handled within your popup. This mostly is done to keep my popup code in one place and all events centrally located within the object.
$('a').live('click', function(e){
e.preventDefault();
popUp.start(this);
});
$('.cancel').click(function()
{
popUp.cancel();
});
var popUp = (function()
{
var count = 10; //number of seconds to pause
var cancelled = false;
var start = function(caller)
{
$('#popUp').show();
timer(caller);
};
var timer = function(caller)
{
if(cancelled != true)
{
if(count == 0)
{
finished(caller);
}
else
{
count--;
$('.counter').html(count);
setTimeout(function()
{
timer(caller);
}, 1000);
}
}
};
var cancel = function()
{
cancelled = true;
$('#popUp').hide();
}
var finished = function(caller)
{
alert('Open window to ' + caller.href);
};
return {
start : start,
cancel: cancel
};
}());
If you run, you will see the popup is displayed and the countdown is properly counting down. There's still some tweaks of course that it needs, but you should be able to see the overall idea of whats being accomplished. Hope it helps!
JS Fiddle Sample: http://jsfiddle.net/u39cV/
You cannot using a confirm native dialog box as this kind of dialog, as alert(), is blocking all script execution. You have to use a cutomized dialog box non-blocking.
You can use for example: jquery UI dialog
Even this has modal option, this is not UI blocking.
Consdier using the javascript setTimeout function to execute an action after a given delay
if (answer){
setTimeOut(function(){
//action executed after the delay
window.location = $(this).attr('href');
}, 10000); //delay in ms
}
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