Javascript Function Removal and Replacement - javascript

My site is AJAX based so I have an window.onbeforeunload = function(){};. However, I have mailto link and when I click those mailto links, the confirm reload pops up, which I don't like. Is there a way to write a function to remove the window.onbeforeunload = function(){};, pull up the mail editor from the mailto link, and then put the window.onbeforeunload = function(){}; back?
Thanks

You could add a script like this after your anchor:
Mail
<script>
(function(w, d){
var anchors = d.getElementsByTagName('a');
var a = anchors[anchors.length - 1];
a.onclick = function(){
var old_unload = w.onbeforeunload;
w.onbeforeunload = null;
w.location = a.href;
setTimeout(function(){
w.onbeforeunload = old_unload;
}, 0);
return false;
};
})(window, document);
</script>
JSFiddle Demo
Note: The first revision did not work, because w.onbeforeunload = old_unload was running before the browser changed to the mailto page. Using setTimeout to make the assignment asynchronous solves that problem.

Related

Phonegap window.open insert innerHTML

I like to add innerhtml content(Just Anchor Link) when an external website is opened.
Below code is used to open the external site in inAppBrowser.
var ref = window.open(url, '_blank', 'location=yes');
I tried with below code to add the innerhtml but its not adding the content to the opened website. Can you please suggest an solution?
ref.addEventListener('loadstop', function() {
//Page loaded! some code here..
ref.executeScript({
code: "var evaluateFeedback =
function() {
return 'Done';
};
"},
function(data) {
ref.document.body.innerHTML =
"<b>Hello, stackoverflow! < /
b > ";
}
);
});
ref is a reference to the inAppBrowser object, you can't do ref.document.body.innerHTML because the inAppBrowser object doesn't have a document property
You are using executeScript in the wrong way, the code you want to inject is the code on the code param.
If you do it this way it will work:
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes,toolbarposition=top');
ref.addEventListener('loadstop', function() {
ref.executeScript({code: "document.body.innerHTML = '<b>Hello, stackoverflow!</b>';"});
});
But that will replace your website content with just the Hello, stackoverflow! message, if you want to append it, you should use
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes,toolbarposition=top');
ref.addEventListener('loadstop', function() {
ref.executeScript({code: "document.body.innerHTML = document.body.innerHTML +'<b>Hello, stackoverflow!</b>';"});
});

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.

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

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...

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