window.open within setTimeout doesn't perform the action - javascript

Why does this call to setTimeout show the alert box but does not do the call to window.open?
If I remove the alert, it doesn't do the window.open either.
// Pause first then open window
function pause_first (url) {
alert (url);
var external_window = window.open(url,'_blank');
external_window.focus();
}
var pause_ret = setTimeout( function() { pause_first(url); }, 1000);

Most likely, because your browser considers it to be a non-user-triggered popup … so it blocks it.

Related

open window and run function on that window

I'd like to open a new window, this window has a list of objects, and these objects should be filtered based on a selection from the previous window. I figured I can filter the list through a function, but how do I run said function?
This is what I am able to do:
var popup = window.open('pageURL');
$(popup.document).ready(function() {
// this is where function should be
popup.alert('HelloWorld');
});
But how do I change the alert to a function?
If I have a function on my other app , function test() { alert('HelloWorld'};
How do I run this function from my first app?
Swapping popup.alert('HelloWorld'); with popup.test(); did not work.
You need the reference to the window opened to call functions in the new window, like:
var oNewWindow = window.open("new.window.url", "mywindow");
oNewWindow.onload = function(){oNewWindow.window.newWindowFunction();};
I ended up with this solution
var popup = window.open('http://s234-0057/actiontracker/SiteAssets/Avvik/html/app.aspx');
var readyStateCheckInterval = setInterval(function() {
if (popup.document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
popup.test();
}
}, 50);
Where I check if the popup window is ready, and when it is, cancel check and run function. Solution is from top answer on this question, by #this.lau_
You can write it like this:
function myFunction(){
alert('HelloWorld');
}
var popup = window.open('pageURL');
$(popup.document).ready(function() {
popup.eval(myFunction + "");
popup.myFunction();
});
myFunction in file that contains this code will run in page with pageURL address.

Pop Up Blocker in Chrome and IE

Below is the piece of code I am using to open a link in a new window say "abc".
If the user again clicks on the same link, it should close and reopen the link in the same window "abc".
window.openOrFocus = function(url, "abc") {
if (!window.popups) {
window.popups = {};}
if (window.popups["abc"]){
var v=window.open("", "abc");
v.close();}
window.popups["abc"] = window.open(url, "abc");
}
But Now, say I click on the link, it opens the URL in a new window named "abc".
Now I go and close the window "abc". and go back and again click on the link.
That time it shows up the pop up blocker.
I am confused as to why this pop up blocker is coming when the I go and manually close the window and try to reopen by clicking on the link.
Happens both in IE as well as Chrome
Probably because you're calling window.open with a blank URL or repeatedly in that case.
You don't need your window.open("", "abc") call; instead, just use the window reference you already have:
window.openOrFocus = function(url, windowName) {
if (!window.popups) {
window.popups = {};
}
if (window.popups[windowName]){
window.popups[windowName].close();
}
window.popups[windowName] = window.open(url, windowName);
};
I would also listen for the unload event so you can remove your reference:
window.openOrFocus = function(url, windowName) {
if (!window.popups) {
window.popups = {};
}
if (window.popups[windowName]){
window.popups[windowName].close();
}
window.popups[windowName] = window.open(url, windowName);
window.popups[windowName].onunload = function() {
delete window.popups[windowName];
};
};
Side note: This is a syntax error:
window.openOrFocus = function(url, "abc") {
// --------------------------------^
I've replaced it with windowName in the code above.

Javascript detect popup window close

I have this code in my popup window (which is opened by parent window):
window.onbeforeunload = closeWindow;
function closeWindow(){
}
The problem is that this code fires when parent window is being refreshed. Is there a way for this code only to fire when popup window is actually being closed?
Hmmm. You could try something like this in the window that opens the popup.
var NewWin = window.open("NewWin", "example.htm", "width=100;height=300;");
// modify styling as necessary etc.
NewWin.onbeforeunload = function() {
window.setTimeout(function() {
if (!NewWin) {
// window has been closed
} else {
// false alarm, just a refresh
}
}, 1000);
}
EDIT: To prevent the window from reopening on parent page refresh, use a similar technique from within the popup
window.opener.onload = function() {
window.opener.NewWin = self;
}
Then change the first line of the code above to:
document.onload = function() {
if (!NewWin) { var NewWin = window.open("NewWin", "example.htm", "width=100;height=300;"); }
}

setTimeout window.open can't take this.href

I'm trying to open the href onMouseOver after 3000ms. But it just popups a blank window. What am I missing?
HTML:
My Rec
JavaScript:
var Popup = null;
function openwindow()
{
var win = window.open()
}
(OK, first off, you need to supply a URL to window.open(), otherwise it doesn't know what page to open to. Aside from that:)
When you do a setTimeout() the value of this is reset in the delayed code.
A quick fix is to extract the URL immediately, and then pass a function into setTimeout() that can use the variable.
<a href="../cc2b/myrec.html"
onMouseOver="var popupUrl = this.href; Popup = setTimeout(function(){openwindow(popupUrl)}), 3000);"
onMouseOut="clearInterval(Popup)">
My Rec
</a>
However, a cleaner solution would be to minimise the code in onMouseOver by setting a timeout in the openhoverpopup function:
<a href="../cc2b/myrec.html"
onMouseOver="openhoverpopup(this.href)"
onMouseOut="clearhoverpopup()">
My Rec
</a>
<script>
var popupTimeout = null;
function openhoverpopup(url) {
popupTimeout = setTimeout(function () {
window.open(url);
}, 3000);
}
function clearhoverpopup() {
clearTimeout(popupTimeout);
}
</script>
You can grab the URL from the element that triggered the mouseover event with either event.target or event.srcElement for older IE browsers.
http://jsfiddle.net/b42pr/1
HTML
Hover
JavaScript
function popURL() {
var url = event.target.href || event.srcElement.href;
console.log("Open URL: " + url);
setTimeout(function(){
window.open(url);
}, 3000)
}
this.href is undefined, I think you're looking for window.location.href:
> this.href
undefined
> window.location.href
"http://stackoverflow.com/questions/18981172/settimeout-window-open-cant-take-this-href"
Also, your function
function openwindow()
{
var win = window.open()
}
Takes no parameters and opens nothing. Change it to
function openwindow(target)
{
var win = window.open(target)
}
Be careful though, most pop-up blockers will block this kind of window.
Try specifying the href outside of the string:
My Rec

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