setTimeout window.open can't take this.href - javascript

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

Related

Avoid onbeforeunload in location.href

I have the code below which asks for confirmation when a user tries to reload the page. It works fine
window.onbeforeunload = function(event) {
return confirm('Confirm refresh');
};
In another part of the code, I am redirecting it to the page using window.location.href It returns a popup whether you want to leave the page. How can I avoid this popup when using window.location.href?
window.location.href = window.location.href.split('#')[0];
You could just set a variable to skip this behaviour :
let skipUnloadConfirm = false;
window.onbeforeunload = function(event) {
if(!skipUnloadConfirm) {
return confirm('Confirm refresh');
}
};
And then change value before setting href (function would replace direct window.location.href assignement and could be reused)
function redirect(url) {
skipUnloadConfirm = true;
window.location.href = url;
}
Or, you can override window.onbeforeunload before calling redirect

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.

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.

window.open within setTimeout doesn't perform the action

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.

Categories

Resources