Send response when window is closed - javascript

The goal
Send true or false when window is closed.
The problem
When I click on a button, a window is opened with window.open(); syntax. What I need seems to be simple: when the window is closed, return to the window that opened the popup a response from the server, that can be true or false — like the Facebook's API does.
Someone knows how can I do this in a simple way?
Spotlight
I don't want to use jQuery because the page's CSS is overwriting the popup's CSS.
Current syntax
HTML:
[...]
<a href="#" class="share" data-networkName="<?php echo $network->name; ?>">
Share</a>
[...]
JS:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.open("share.php?network=" + networkName");
});

This is what I came up with:
UPDATE
receive.html
Share
<script>
var new_window = null;
function openWindow() {
new_window = window.open('return.html');
}
// Callback Function that we will call in child window
function sendMessage(message) {
alert(message);
new_window.close();
}
</script>
return.html
Mark As Shared
<script>
function messageParent() {
// Calls sendMessage function on the parent window.
window.opener.sendMessage("Hello World!");
}
</script>
You could then handle the return value that you would like to in the sendMessage function in the parent window.
This is the simplest method I could come up with. Please let me know if this works.

Try this:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.onbeforeunload = function() {
window.open("share.php?network=" + networkName");
}
});
UPDATE
main.php's script:
$(".share").on("click", function(event) {
event.preventDefault();
var networkName = $(this).data("networkName");
window.onbeforeunload = function() {
window.open("share.php?network=" + networkName");
}
function send(msg) {
//send msg to db or store as cookies
}
});
popup.html's script: [Let's say you have a share button called '#popup-btn']
$('#popup-btn').click(function() {
window.opener.send('MSG SENT FROM POPUP {THEY SHARED SOMETHING}');
});

Related

execute js function after reloading page [duplicate]

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

Display iframe when user wants to close the webpage

I need to display an iframe when a user wants to close my web page. I tried to do that using jQuery (I'm really not good in jQuery), but I cannot even display a message before the browser's tab is closed. I tried:
<script>
$(window).bind('beforeunload', function(){
return "Do you really want to leave now?";
});
</script>
also tried
<script type="text/javascript">
$(window).on('beforeunload', function() {
return '....';
});
</script>
It is possible that I have missed something basic...
Display iframe code :
window.onbeforeunload = function () {
$("#dialog").load("iframecontent.htm").dialog({dialogoptions});
};
Display messsage :
window.onbeforeunload = function () {
return "Do you really want to close?";
};
OR
window.addEventListener("beforeunload", function (e) {
var msg= "\o/";
(e || window.event).returnValue = msg;
return msg;
});

On close tab ask for unsaved changes and then reload the page - How?

I've come across a nasty website that managed to refresh the page every time I tried to close the tab. Basically you couldn't close that page. I got around it by disabling javascript on that page.
How do they do it?
I've tried location.replace inside onbeforeunload and it doesn't work:
window.onbeforeunload = function(e) {
window.location.replace(window.location.href);
};
Here is the source of the page in question, where I don't get how they do it:
<script type="text/javascript">
function c(b)
{
document.write(b);
}
function wrapped3(d)
{
return d.replace(/(.)(.)/g, '%$1$2');
}
function wrapped(b)
{
var tmp = window['decodeURI' + 'Component'];
return tmp(wrapped3(b))
}
function show_page(a)
{
c(wrapped(a)
.split('{{addr}}').join('//ip')
.split('{{country}}').join('Great Britain')
.split('{{region}}').join('London, City of')
.split('{{city}}').join('London')
.split('{{ltude}}').join('//latitude')
.split('{{referrer}}').join('//url here')
);
}
show_page('//long string here');
</script>
window.onbeforeunload is the correct solution, here is an example:
var popit = true;
window.onbeforeunload = function() {
if(popit == true) {
popit = false;
return "Are you sure you want to leave?";
}
}
http://jsfiddle.net/SQAmG/3/

jquery window.onbeforeunload not working with a href=javascript function

i have below code to invalidate session on window unload
window.onbeforeunload = function(event) {
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
console.log("closing the browser, invalidating the session");
$.ajax({
url : "/inValidateOnBrowserClose.html",
type : "get",
cache : false,
}).done(function(data) {
console.log(" invalidated session on browser close event");
});
}
return true;
};
$(function() {
$("a").click(function() {
window.onbeforeunload = null;
});
$("button").click(function() {
window.onbeforeunload = null;
});
});
all working fine, but i have a page where i have a dynamically created buttons.
<span class="myButton"><a href="javascript:submitForm" >Update </a></span>
when i click above anchor (button) my window unload event is getting called (in my case it should not get called), i am surprised why $("a").click(function()) is not called in first place, i am trying to fix this but no luck. Thanks for your answers
You need to use delegate here like below for binding click events to dynamically generated elements :
$(function() {
$(document).delegate("a","click",function() {
window.onbeforeunload = null;
});
$(document).delegate("button","click",function() {
window.onbeforeunload = null;
});
});
And this works for already existing elements, so no need to write separate click binding.
For firefox user delegate function may not work so they can use on. please see below code
$(function() {
$("a").on("click",function() {
window.onbeforeunload = null;
});
$("button").on("click",function() {
window.onbeforeunload = null;
});
});
Stackoverflow Issue

using onbeforeunload event, url change on selecting stay on this page

Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.

Categories

Resources