I want to prohibit the Back function of the browser.
Therefore I write the following codes in html.
<body>
<script type="text/javascript">
<!--
history.forward()
//-->
</script>
</body>
but'The above "history.forward()" did not work suddenly when
I coding html and some javascripts.
What's wrong?
In addition, please teach the different method that had a similar function.
Thanking you in advance.
Using the history object
window.history.go(positive integer)
will take you forward through history, so
window.history.go(1)
will take you forward one page.
Also, make sure you're referencing the window object.
window.history.forward()
should also work
My recommendation is to not restrict the user's browser. Web browsers have back buttons and that's the way it is. You should architect your application so that it works when the user uses the back button, such as by expiring the page and properly handling the refresh of a previous page. If disabling the back button is some attempt at security, realize that there are ways around it, especially if javascript is disabled.
If I ended up on your site and found that everytime I hit the back button the page would ignore it I would be very unhappy. You can't know that you are the first site in the browsing history.
In my opinion, having javascript functionality to control the user's history was a bad addition.
Related
So on our page we have a "Quick exit" button (really a link styled as a button), which takes you to Google. We wanted to keep it simple in terms of functionality, but we decided it would probably be a good idea to at least use window.location.replace for navigation to prevent browser back, so we're using a click handler. However I thought it might also be a good idea to add href="https://google.com" simply so that the user will be able to see where the button is going if they hover over it. But, I'm just not sure if this would be violating some unwritten rule, since technically the href isn't doing anything, and is only there to "trick" the user into thinking they're clicking a normal link when it's really running JavaScript. Any thoughts? Thanks.
If you really want to prevent default browser back behavior (which some consider user-unfriendly), then what you're doing is perfectly reasonable, and could even be better than the alternatives. It not only gives the user an indication of what clicking will do, it'll also allow those few users with JavaScript disabled to navigate your page.
An explicit href may also help web scrapers like Googlebot find pages on your site (though this won't matter if the link is external and to some place you don't care about SEO for).
i want to know is there any way we can know browser's events.. like : clicking on BACK button, FORWARD button, REFRESH button by javascript.
These specific browser events are not available as it would be vulnerable to severe privacy violations. Privacy is something browser vendors hold sacred and a key selling (proverbial) point. All browsers allow you to know is when a user enters or leaves your page for which Kamui pointed out the technical details.
Within the same site, it's possible to achieve some browser event tracking using cookies and javascript. For example track wether users click on a hyperlink and label it as a forward event and when a user leaves the page without clicking on a hyperlink it could be one of:
browser url input
back action
javascript location.href replace
The location.href replace can be tracked as well when you have full control over all javascript, just use a helper method with tracking code instead of directly chaning location.href.
That leaves browser url input and the back action. With cookies and request headers (getting the referrer) it is possible to get close to finding out the forward and back events, though not 100%, but pragmatically, 99% sure is good enough.
Figuring out the refresh event is easy with request headers (referrer), if the current url matches the referrrer, it's a refresh event.
Now I offer no code or definite solution, but I outlined what you could do to track back, forward and refresh events within a single domain context. It won't be a quick and easy way to implement it and as far as I know, there's no framework in existance that reliably tracks browser events or even comes close to what I described above.
A more common/lazy technique to achieve something similar is to create a single page app, for which there are many frameworks available. Just google single page app framework, but thats a pretty heavy solution with other implications that I won't go into now.
You can not capture (for example run some piece of code when user presses Back button) them, however, you can direct your pages in history by using:
history.go
history.back
history.forward
More about JS History object.
As #sarfraz says you cannot capture the back and forward button clicks but you could call
window.onbeforeunload = function(){alert("you just tried to leave the page");};
which should be triggered when either the back/forward/refresh buttons are clicked to perform an action, unfortunately you can't tell if they are going back or forward. Please note don't alert a message it's really annoying when trying to exit a page.
EDIT
you can also do this in jQuery if you have it
$(window).unload( function () { alert("Bye now!"); } );
I want to be able to disable history.go(-1) on certain pages.
I'm wondering if there is a way to clean up the Javascript's history object. Any ideas?
history.go() seems to not be functioning too well on certain browsers such as IE. Is that true? Any solution for that?
You can over-write the go method, but it doesn't get you much
history.go = function(){};
This will disable all uses of history.go, and not just when you pass a -1.
And as others have pointed out - this doesn't stop the user from using the Back button on their browser.
The best you can do to "disable" history is to open your page in a new window, which will have no history. Pages opened in a new window don't have a back button enabled and history.go(-1) will not do anything
Short of that, there is nothing you would (or should) be able to do.
Revised to make an implication explicit. I thought I was being clear, but apparently I was not.
You cannot override this browser behavior. If you could there would be mayhem as malware would try to take over everyone's history.
If you're trying to disable the browsers BACK button this is simply not possible. Would you like it if websites could mess around with your browsers functionality?
You've got two options.
Load pages with post request, this will prevent users from using back-button as you can trap the reload on server-side. (You need to wrap all hyperlinks with js though, so a bit of work, and the solution is quite ugly.)
Use DOM to load content into page. History won't be able to backtrack it. (or am i wrong here :-| )
describe your problem more clearly, there's probably better solutions for where you need to go.
Put this in your shared page header:
<body onLoad="history.forward()">
It will always force the user to the most recent page they've visited on your website.
This is ugly, but might work:
$(document).load(function(){
document.location.href = document.location.href + "#";
setInterval(function(){
if (window.location.hash != '#')
document.location.href = document.location.href + "#";
}, 100);
});
ugh!
Desmond,
My boss doesn't want the back button to work on the landing page.I know it's stupid but what can I do.
What about using default page, (index.php or whatever) to point forward.
index.php:
header('location:start.html');
//or likewise with js,
document.location = 'start.html';
start.html:
my real start
as user hits the back-button, the index.php will redo the forwarding.
regards,
Thanks for all the responses. After two days of juggling, I came up this solution, for now.
I use PHP to output a class to the body tag if it's the current page is the front page. Something like
<body class='front'>
and then use jQuery to enable/disable "history.go(X)" on the fly.
$(document).ready(){
if($('body.front').length>0){
$('#backbutton').click(function(){ window.history.back(); });
}else{
$('#backbutton').unbind('click');
}
}
In fact the project that I was working on require the site inside an iframe to disable the element that triggers the back button of the parent window. The js becomes:
var backbutton=parent.window.getElementById('#backbutton');
$(document).ready(){
if($('body.front').length>0){
$(backbutton).click(function(){ window.history.back(); });
}else{
$(backbutton).unbind('click');
}
}
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.
Is there any reason to NOT have a webpage retrieve it's main content on the fly?
For example, I have a page that has a header and a footer, and in the middle of this page is an empty div. When you click on one of the buttons in the header, an http GET is done behind the scenes and the .innerHTML() of the empty div is replaced with the result.
I can't think of any reason why this might be a bad idea, but I can't seem to find any pages out there that do it? Please advise!
It's not unheard of, but there are issues.
The obvious one is that some users have javascript turned off for security reasons, and they will not be able to use your site at all.
It can also negatively impact handicapped users that are using assistive technology such as a screen reader.
It can make it harder for the browser to effectively cache your static content, slowing down the browsing experience.
It can make it harder for search engines to index your content.
It can cause the back and forward buttons to stop working unless to take special steps to make them work.
It's also fairly annoying to debug problems, although certainly not impossible if you use a tool such as Firebug.
I wouldn't use it for static content (a plain web page) but it's certainly a reasonable approach for content that is dynamically updated anyway.
Without extra work on your part it kills the back and forward history buttons, and it makes it difficult to link to the pages each button loads. You'd have to implement some sort of URL changing mechanism, for example by encoding the last clicked page in the URL's hash (e.g. when you click a button you redirect to #page-2 or whatever).
It also makes your site inaccessible to users with JavaScript disabled. One of the principles of good web design is "graceful degradation"--enhancing your site with advanced features like JavaScript or Flash or CSS but still working if they are disabled.
Two considerations: Search engine optimization (SEO) and bookmarks.
Is there a direct URL to access your header links? If so, you're (almost) fine. For example, the following code is both SEO friendly and populates your page as you desire:
Header Link
The catch occurs when people attempt to bookmark the page they've loaded via JavaScript... it won't happen. You can throw most of those potential tweets, email referrals, and front page Digg/Reddit articles out the window. The average user won't know how to link to your content.
Where did you read it is a bad idea? It purely depends on requirements whether or not content will be populated on-the-fly. In most cases, however, the content is loaded along with the page not on-the-fly but if you need your content on-the-fly, it shouldn't be a bad idea.
If your content is loaded via javascript and javascript is disabled on users' browser then definitely it is a bad idea.
I cant think of a bad reason for this either (other than possibly SEO), one thing that would probably be a good idea is to load the data only once. ie
Show Div1 - do ajax/whatever only if the innerhtml is blank
Show Div2 - do ajax/whatever only if the innerhtml is blank
<div1></div>
<div2></div2>
This should keep the server load down so the divs content is only loaded once.
Cheers
This is pretty standard behavior in ajax enabled sites.
Keep in mind however that extra effort will be needed to:
ensure the back button works
link to (and bookmark) specific content
support browsers with javascript disabled.