When the refresh button is pressed, I would like to send the user to a different page using PHP or javascript.
That is,
if (refresh pressed) header('Location: Some_Page.php');
Can anyone tell me how is it possible?
Although you tagged your question as javascript, you did also tag it as php
You could use sessions for this. Here is what I tried that worked.
I set the conditional statement to 10 (for testing purposes), but you can make it as 1 or any other number you wish.
N.B.: ob_start(); is required, otherwise it will throw an headers already sent error message.
<?php
ob_start();
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
if ($_SESSION['views']== 10){
header("Location: http://www.example.com/");
}
?>
Footnotes: If you use this, session_start(); (and maybe ob_start(); if using header()) needs to be inside all files using the same session, and at the top as shown.
So, I don't think you can hook into a specific page refresh event (I don't think it exists), you can hook into a page unload via javascript, which would be fired on a page refresh event. You would use the onunload or onbeforeunload event to trigger saving the state in cache or a cookie. (you could also on timeouts set the state every x seconds during normal gameplay)
You cannot alert or redirect with hooking into the unload or onbeforeunload events.
the following was my original suggestion, before I tested and found you cannot do the page navigation from the onunload and onbeforeunload events
You would also want to set a boolean saying game place has started, check for the boolean in the unload event (set that boolean to false after game is complete). That way you do not do a redirect when the user wants to actually navigate away from your game.
window.onbeforeunload=function(){window.location.replace(...)};
window.location.href=... would also work in the context of the onunload event.
Event click on Refresh button equals event of exiting current page. Use next:
// jQuery
$('body').bind('beforeunload',function(e){
e.preventDefault();
var url = "http://stackoverflow.com";
$(location).attr('href',url);
});
// JS
window.onbeforeunload = function (e) {
e.preventDefault();
var url = "http://stackoverflow.com";
// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else window.location.replace(url);
};
Related
i'm using the 'beforeunload' event to detect the refresh event from the webpage.how to stop refresh the page from beforeunload event and i should not show alert message
window.addEventListener("beforeunload", this.onUnload);
onUnload = e => {
e.preventDefault();
// how to stop refresh the page from here and i should not show alert message.
//it is showing alert message. i no need to show the alert.
e.returnValue = "sure do you want to reload?";
}
It is not possible to prevent unloading a page without notifying the user.
Imagine you want to go to github.com at a time you are viewing stackoverflow.com - but it will simply prevent you from navigating away!
However, there was a time some browsers used to prevent unloading silently when you assign an empty string to the returnValue. But I believe that age of evil is gone now.
When i understand your following comment corectly, then you simply need to return zero, or false. So in your function you write:
onUnload = e => {
//e.preventDefault();
return false;
}
When i do this, i get an automated response from the Browser (for me its Chrome), if i really wanna close this website. And its in my language, so its i18n-compilant
It basically says "Are you sure you wanna refresh/close this website, data may get lost" and than 2 buttons with "Refresh/Close" and "Abort"
Using the following function to prevent users from going back to previous page if the page they are on currently has the id #home. But this function doesn't even fire off. No alerts. Nothing wrong with the link to script file as I have other scripts running fine on that file.
document.addEventListener("backbutton", function (e) {
alert("Back button pressed");
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
alert(activePageId);
if (activePageId == 'home') {
e.preventDefault();
}
}, false);
Unless you have created a custom event there is no onbackbutton event I know of. You are after onbeforeunload
Clients don't like it when you block navigation. You should consider other solutions to you problem rather than block navigation. Sure as .... the next thing the client will do is close the tab and a good chance you will never see a session with that client again.
I'm having an issue in IE9 with onbeforeunload -- when the code below is run it repeatedly brings up a dialog asking if you want to stay or leave the page.
I modified my code to prevent default functioning based on this thread to no avail.
Any help on this would be much appreciated.
Code Sample:
window.onbeforeunload = function(e) {
e.preventDefault();
e.returnValue = false;
saveFormData();
return null;
}
function saveFormData() {
$.post("<?php echo site_url('resume/cleanup'); ?>", { resume_id: "<?php echo $this->session->userdata('resume_id'); ?>" } );
}
You cannot send an AJAX request while the page is unloading as most browsers block it. You should ask the user to stay on the page if there is dirty data. That's all you should do from your onbeforeunload handler
Try your code without calling $.post and it should behave as expected
The only thing you are allowed to do in an onbeforeunload handler is display a dialog. You specifically don't get any extra time to perform tasks which may take time to complete, like firing off HTTP requests — the user has asked to leave your site; aside from asking them politely whether they want to stay, you aren't allowed to make them stay (even while you clean up).
https://developer.mozilla.org/en/DOM/window.onbeforeunload
Here is the situation :
If I am in page-1 now I am clicking a link from page-1 to navigate to page-2. Before page-2 is loaded I am hitting escape so that still I am staying in page-1.
At that point I want to track that event.
Is there any JavaScript event so that I can track the above scenario?
More Info :
To avoid concurrent request to the "page-2", when the user clicks a link from page-1 I am redirecting to page-2 and disabling the link (to avoid multiple request to "page-2). At this point when we hit Esc and abort loading page-2, I need to enable the link again in page-1.
I tried using this code:
<html>
<head>
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event; //IE Compatibility
alert(e.keyCode);
}
</script>
</head>
<body>
Stack Overflow
</body>
</html>
It detects any key pressed while you're on the page. Once you click on the SO link and hit escape, nothing happens. The browser is already receiving a response from the SO server and is starting to process it, this page has already been "left", despite appearances when you see "Waiting for http://stackoverflow.com" in your browser's status bar.
Your idea of handling this event is plain wrong. Blocking the button is required to make the user unable to do double post data. However, the request is sent instantaneously(!) after the click on the link.
So, if you click the link once, stop the page, then click second time - it will submit it twice, and that is not what is intended to happen.
Two events are triggered when the page unloads.
window.onUnload
window.onBeforeUnload
You can use these events to cancel the unload of the page, however after that, there page is considered done.
What you can do is make the page wait 5 secs or so before going to the new page:
eg:
window.onunload = (function() {
var time = new Date();
var cancel = false;
window.onkeypress = function (e) {
if ((e || window.event).keyCode == 27) cancel = true;
};
while(time > new Date() - 5000) {
if (cancel) return false;
}
});
In fact that may cause some browsers to hang since you're taking up all process time given to the JS script. ie: in the while block.
You could probably avoid that by doing a blocking function call, that isn't so process intensive, like one that is bound by network latency. eg: XMLHttpRequest() etc. I don't think calls that are queued such as setTimeout() will work here, as they don't block.
Since the <a href> tag tells the browser to move to another page, it's up to it to decide if it will still have your script running. If I were it, I wouldn't listen.
If you want to override that, I guess you should tell the browser not to listen to that particular onClick event, and put a callback in place that loads the target page in the background. This assures your page is still active. After the target page has loaded (by your script), you could kindly ask the browser to update itself with the received content.
So that's the theory. I have no idea if the DOM lets you just override the content of a loaded page, but I guess it does.
Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the hashchange event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.
What I ended up doing was creating an object as such:
var pageload = {
ignorehashchange: false,
loadUrl: function(){
if (pageload.ignorehashchange == false){
//code to parse window.location.hash and load content
};
}
};
Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:
window.addEventListener("hashchange", pageload.loadUrl, false);
Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:
pageload.ignorehashchange = true;
and then the following line after each hash modification line:
setTimeout(function(){pageload.ignorehashchange = false;}, 100);
So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.
Check out history.js. There is a html 5 statechange event and you can listen to it.
onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.
Did you took a look at this? http://developer.yahoo.com/yui/history/