redirect to a different page - javascript

I need some help here:
I am writing code to redirect a user to a different page and execute some code, if the user closes the window while he is working on something:
<script type="text/javascript">
window.onbeforeunload = function() {
location.assign('http://www.somesite.com');
return "go?";
}
</script>
Now the code works fine if the user presses cancel. But if he presses Ok, the windows closes without a redirect.
I just need a working code that does one simple thing - redirect the user if the window is closed - can anyone suggest me the code for it
I know that most of you will say that I should not be doing this and I know that this is not the best practice. But if any one of you has written a successful piece of code, please share it here.

Actually you should not. All the browsers make sure you don't.
Even if you find a way, rest assured that it will be on every browser's bug list, next day morning.
If the user wants to close the window there is nothing you can do.
He will.
The only thing you can do is ask politely "Are you sure?"

Related

How to make a postback when the user clicks the back button?

I have a webforms web app, and all I need to do is, when a user clicks on the browser back button, I want to make a post-back or reload my page so it makes the post-back itself so new data is loaded.
I am using a library called jQuery-backDetect
which allows me to detect browser's back button click and I try to do is to make a post-back using __doPostback('arg1', 'arg2'). But it won't work at all.
And the strangest thing here is that, if I have the browser's debugger (in developer tools) open, or I pause the code execution using a breakpoint, it works perfectly. Here is a simple code I have written:
$(window).load(function(){
$('body').backDetect(function(){
// Callback function
debugger;
__doPostback('arg1', 'arg2');
});
});
I have tried to go through all the question here but they didn't help.
As strange as the question sounds, I really hope someone can help me. Thanks
You might consider wrapping the page content in an UpdatePanel, that might help create the behavior you are looking for.

Beforeunload is not working to redirect user to another page, how can I redirect user to another page/url when he attempts to close a window/tab?

My following code isn't working to redirect the user to another page:
$(window).on('beforeunload',function(){
window.location.href="http://www.google.com;
}) ;
I want the user to be redirected to another page when he attempts to close the tab.
What's the alternative and appropriate way to achieve this?
*Don't do it*
But it is possible with the user's permission; you can achieve something like this (took me a while to find a website that was happy in a frame)
window.onbeforeunload = function () {
window.setTimeout(function () { // escape function context
window.location = 'http://bbc.co.uk';
}, 0);
window.onbeforeunload = null; // necessary to prevent infinite loop
// that kills your browser
return 'Press "Stay On Page" to go to BBC website!';
// pressing leave will still leave, but the GET may be fired first anyway
}
Demo
I don't think this is possible.
There are some things you can can do in this event but that is severely limited due to spammers back in the day. They used to have animated text in the window statusbar which would obscure link href's so you would be clicking blind and open tons of windows when you tried to leave so that you were essentially trapped on the site.
This got to be such a problem that as far as I recall it was one of the "features" that Firefox bragged about solving when it first launched.
It was toned down to being able to beg them to stay with a dialog box but then that was abused as people worded it like official system messages and tricked people.
Now most browsers let you request a "stay on page / leave page" dialog but dont give you any control over the wording.
Here are some docs that list your options:
https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

Is there a way to disable the address bar on a browser on page load

Basically I am creating a landing page for customer wifi, we already have a way of the page being the first to load, now I want to go one further. I want the customers to agree to our usage policy before they can continue, so basic stuff, create a page, add T&C's and a check box and an accept button, check to box click accept and you are on your way to internet awesomeness!
Except users could bypass this by changing the address in the address bar.
What I want to do is disable any address changes, thus disabling the address bar
Is it possible to do this using a simple javascript? Is there an easier way of solving this issue?
This works for me:
<html>
<script for="window" event="onload">
window.open('main.jsp',
'Window',
'width=800,height=600,resizable=0,status=0,toolbar=0');
// Hack to bypass the confirm alert on window close.
window.opener = window.top;
window.open('', '_self', '');
window.close();
</script>
</html>
This opens a new window on main.jsp with reduced abilities and closes the launched window (which comes from index.jsp).
And - contrary to popular belief - the new window does not have an address bar. In fact it also doesn't have a close box either but you can change that.
P.S. - This might only work for IE.
you cant lock the browser address bar, no.
normally they just route every page request, except from your domain, to your page until someone has accepted/verified
You can use javascript confirm box:
var result=confirm("Press a button!")
if (result==true)
{
alert("You pressed OK!")
}
else
{
alert("You pressed Cancel!")
}
}
And make some condition..if the user presses ok then do something, else you can redirect him to some other page...though these alerts really interfere with UI experience..

Prevent any form of page refresh using jQuery/Javascript

Once the user is on my page, I do not want him to refresh the page.
Anytime, the user hits F5 or refresh button on top. He should get an alert saying
You cannot refresh the page.
Also if the user opens a new tab and tries to access the same url in prev tab he should get an alert
You cannot open same page in 2 tabs
Anyway I can do this using JavaScript or jQuery? Point one is really important.
#1 can be implemented via window.onbeforeunload.
For example:
<script type="text/javascript">
window.onbeforeunload = function() {
return "Dude, are you sure you want to leave? Think of the kittens!";
}
</script>
The user will be prompted with the message, and given an option to stay on the page or continue on their way. This is becoming more common. Stack Overflow does this if you try to navigate away from a page while you are typing a post. You can't completely stop the user from reloading, but you can make it sound real scary if they do.
#2 is more or less impossible. Even if you tracked sessions and user logins, you still wouldn't be able to guarantee that you were detecting a second tab correctly. For example, maybe I have one window open, then close it. Now I open a new window. You would likely detect that as a second tab, even though I already closed the first one. Now your user can't access the first window because they closed it, and they can't access the second window because you're denying them.
In fact, my bank's online system tries real hard to do #2, and the situation described above happens all the time. I usually have to wait until the server-side session expires before I can use the banking system again.
You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.
Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.
Although its not a good idea to disable F5 key you can do it in JQuery as below.
<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableF5);
});
</script>
Hope this will help!
Back in the ole days of CGI we had many forms that would trigger various backend actions. Such as text notifications to groups, print jobs, farming of data, etc.
If the user was on a page that was saying "Please wait... Performing some HUGE job that could take some time.". They were more likely to hit REFRESH and this would be BAD!
WHY? Because it would trigger more slow jobs and eventually bog down the whole thing.
The solution?
Allow them to do their form.
When they submit their form... Start your job and then direct them to another page that tells them to wait.
Where the page in the middle actually held the form data that was needed to start the job.
The WAIT page however contains a javascript history destroy. So they can RELOAD that wait page all they want and it will never trigger the original job to start in the background as that WAIT page only contains the form data needed for the WAIT itself.
Hope that makes sense.
The history destroy function also prevented them from clicking BACK and then refreshing as well.
It was very seamless and worked great for MANY MANY years until the non-profit was wound down.
Example:
FORM ENTRY - Collect all their info and when submitted, this triggers your backend job.
RESPONSE from form entry - Returns HTML that performs a redirect to your static wait page and/or POST/GET to another form (the WAIT page).
WAIT PAGE - Only contains FORM data related to wait page as well as javascript to destroy the most recent history. Like (-1 OR -2) to only destroy the most recent pages, but still allows them to go back to their original FORM entry page.
Once they are at your WAIT page, they can click REFRESH as much as they want and it will never spawn the original FORM job on the backend. Instead, your WAIT page should embrace a META timed refresh itself so it can always check on the status of their job. When their job is completed, they are redirected away from the wait page to whereever you wish.
If they do manually REFRESH... They are simply adding one more check of their job status in there.
Hope that helps. Good luck.
No, there isn't.
I'm pretty sure there is no way to intercept a click on the refresh button from JS, and even if there was, JS can be turned off.
You should probably step back from your X (preventing refreshing) and find a different solution to Y (whatever that might be).
Issue #2 now can be solved using BroadcastAPI.
At the moment it's only available in Chrome, Firefox, and Opera.
var bc = new BroadcastChannel('test_channel');
bc.onmessage = function (ev) {
if(ev.data && ev.data.url===window.location.href){
alert('You cannot open the same page in 2 tabs');
}
}
bc.postMessage(window.location.href);
Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.
However, a better solution is to synchronize the two sessions if possible like in google docs.

disable javascript popup on refreshing page

I have written code like this to throw a pop up when my website is closed. But this throws the pop up even if i refresh my page. Please help me to throw popup only when i close the browser of that website. (disable popup on refreshing page)
<body onunload="javascript: exitpop()">
<script type="text/javascript">
function exitpop()
{
my_window= window.open ("","mywindow1","status=1,width=600,height=400");
my_window.document.write('<h1>My Team</h1><p>Thank you</p><p>If you accidentally closed website click here to go back to our website</p>');
}.
onUnLoad is called on a refresh because the browser is requesting a new page (well, the same page in the case of a refresh, but it is still a new call).
I am not sure if there is a way to check where the user is going next, but if there is you could compare it to their current url, if they are the same then the user is just refreshing and the script doesn't need to be run.
Good luck
Sadly, this is not possible. To the browser, it is essentially the same action.
However, if you just use a confirm() box, you can catch a user that is trying to leave without linking them back. If they are refreshing or if they really want to leave, hitting "OK" will allow that action to occur.
Let me know if you need this explained further.

Categories

Resources