Windows.open - how do I handle when it's being closed? - javascript

By calling window.open I'm opening a new window with external website from my Sinatra application:
%a{:href=>"some_external_website.com", :target=>"blank", :onclick=>"popupWin = window.open(this.href, 'test', 'location,width=600,height=500,top=0'); popupWin.focus(); return false; window.open('')"}
I want to handle a moment when an user is closing a window. How can I do it? Of course, in javascript.

Add an onunload handler to the window. Using your current approach:
var popupWin = window.open(this.href, 'test', 'location,width=600,height=500,top=0');
popupWin.focus();
// add an onunload handler
popupWin.onunload = function () { ... };
return false;
window.open('') // this is dead code, unconditional return above...

Related

JavaScript OAuth Popup window handler code

I'm using oAuth to login or sign up using gmail account and decided to use popup window to do it. I found a snippet here which describes the process. But I can't understand how I'll be able to get the values or code if the user logged in with his email.
I can open the modal by this:
//Authorization popup window code
$.oauthpopup = function(options)
{
options.windowName = options.windowName || 'ConnectWithOAuth'; // should not include space for IE
options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=400';
options.callback = options.callback || function(){ window.location.reload(); };
var that = this;
log(options.path);
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
that._oauthInterval = window.setInterval(function(){
if (that._oauthWindow.closed) {
window.clearInterval(that._oauthInterval);
options.callback();
}
}, 1000);
};
And use that as follows:
$.oauthpopup({
path: urltoopen,
callback: function()
{
log('callback');
//do callback stuff
}
});
But now, I'm wondering how to auto close the popup and pass parameters from popup window to the main window.

Opening two instances of InAppBrowser (_system and _blank) prevents events from triggering

We’re currently developing an app with cordova and the InAppBrowser plugin. We're trying to spawn two different IAB instances at the same time. One with the _system browser and another with the _blank option.
The problem we have is that once we open the instance of _system browser, it seems we lose the reference to the previous browser. For this reason, the close event never triggers on the _blank IAB after the _system browser is closed.
This is how the actual code looks like.
// Opening iab main window
var ref = window.open(global.chat_mediador, '_blank','location=no,toolbar=yes');
var handleEvents = function(event) {
// Closing the iab window
if (event.url.match('#close')) {
ref.close();
}
// Trigger custom event
if (event.url.match('#openccard')) {
window.open('https://www.test.example.url.com?customerID=' + event.customerId, '_system', 'location=yes');
}
}
// InAppBrowser events
// This events are duplicated because loadstop works on android and
// loadstart works on ios.
ref.addEventListener('loadstart', handleEvents, false);
ref.addEventListener('loadstop', handleEvents, false);
// Removing the dialog when we close the chat
ref.addEventListener('exit', function(event) {
generali.dialog.close();
}, false);
As you can see we open the first url within the application with the _blank option. Then if in the child application a button is pressed we want to open an instance of a browser in the _system browser.
We’ve tried (without luck) to:
Have a separate reference for the _system browser.
window.open(global.url_ficha + customerId, '_system','location=no');
var cardsRef = window.open(
'https://www.test.example.url.com?customerID=' + customerId,
'_system',
'location=yes'
);
Trigger a custom event outside the reference of the _blank browser
if (event.url.match('openccard')) {
var customerId = event.url.split('openccard-')[1];
var evt = document.createEvent("Event");
evt.initEvent("openccard",true,true);
evt.customerId = customerId;
document.dispatchEvent(evt);
}
Anyone has an idea of what's happening?
It seems that you need to initialize the IAB each time you do a new window.open() if you don't do that the event listeners don't work.
If I use that code it works like a charm.
window.openIAB = function(url, target, options) {
var self = this;
var ref = window.open(url, target, options);
var handleChildEvents = function(ev) {
if (ref != undefined) {
// Closing the iab window
if (ev.url.match('#close')) {
ref.close();
ref = undefined;
}
// Opening card url with system browser
if (ev.url.match('#openccard')) {
var customerId = ev.url.split('#openccard-')[1];
self.ref2 = self.openIAB(
'https://www.test.com?customerID=' + customerId,
'_system',
'location=yes'
);
}
} else {
console.log('InAppBrowser has no reference');
}
};
ref.addEventListener('loadstart', handleChildEvents);
ref.addEventListener('loadstop', handleChildEvents);
ref.addEventListener('loaderror', function(ev) {
console.log('error while loading page');
ref.close();
ref = undefined;
});
ref.addEventListener('exit', function(ev) {
dialog.close();
});
return ref;
};

Send response when window is closed

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}');
});

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.

Calling Javascript function on browser close

I have a site, now what I want is when user switch to some external site, then an Ad should be popped up, and also when user close the browser window, the Ad should get popup, I have used onunload, but it shows the message on clicking every link, and also I used on beforeunload, it does almost everything, but it do the same as onunload...
Please anyone have some idea how should I achieve this?
This doesn't prevent popup appearing on page refresh, but does this job as requested:
<script>
var isLinkClicked = false;
// Either plain JS solution:
var links = document.getElementsByTagName('a');
var l=links.length;
while (l--) {
links[l].addEventListener("click", function() {
isLinkClicked = true;
}, false);
}
// Or jQuery solution:
$("a").live("click", function() {
isLinkClicked = true;
});
// And then Unload event listener:
window.addEventListener("unload", function(evt) {
if (isLinkClicked) {
isLinkClicked = false;
return false;
}
// here comes the rest of the code
}, false);
</script>

Categories

Resources