Avoid onbeforeunload in location.href - javascript

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

Related

How to get the web page to redirect?

The thing is that is not working is that the page does not redirect to another page, weather if it is wrong or right. I want the page to redirect to another page if the user guesses the generated word right.
you just need to preventDefault the form submission,
use this code to prevent it
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
})
function myFunction() {
if (document.getElementById("Enter_the_word").value == "KEYBOARD") {
location.href = 'index4.html';
} else {
location.href = "index.html";
}
}
Your code has no issues but please try this reversed condition. If it helps you.
MY EDITED CODE BELOW -----------------
var answerArr = ['KEYBOARD','MATH','FOOTBALL'];
if(answerArr.includes('MATH')){
location.href = 'index4.html';
}else{
location.href = 'index4.html';
}
Like this

JS don't opening link if else

Alerts are working in both conditions but I can't make a transfer to my HTML link if the password is correct
I ALSO TRIED - document.location.href / window.location.href / document.location.replace
document.querySelector('#submit').onclick = function () {
var pass = document.querySelector('#pass').value;
var passrepeat = document.querySelector('#passrepeat').value;
if (pass === passrepeat) {
//alert("GJ")
local.href = "SuccessfulLogin.html"
}
else {
alert("Wrong pass")
}
}
The correct is window.location.href
and also use event.preventDefault() in submit function.
document.querySelector('#submit').onclick = function (event) {
event.preventDefault()
...
}
window.location.replace("SuccessfulLogin.html");
window.open("SuccessfulLogin.html", "_self");
window.open("SuccessfulLogin.html")
Would usually open in a new tab but the "_self" parameter makes it open in the same tab.

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/

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.

Add a javascript alert when a user tries to close the current tab in browser

I am working on asp.net(c#).I try to add a javascript alert when a user tries to close the current tab in browser. The code is not working in Chrome.Please can any one help about this topic.
This is my code:
<script type="text/javascript">
window.onbeforeunload = function close_window() {
var r = confirm("Do you want to view other topics?");
if (r == true)
{
alert("You pressed OK!");
var Url = "http://stackoverflow.com/";
window.location = Url;
return false;
}
else
{
window.close();
}
}
Remove the () when you're calling the function.
It should be:
window.onbeforeunload = function close_window {
Actually, try this.
function close_window() {
...
}
window.onbeforeunload = close_window;
And yes--it's really bad practice.

Categories

Resources