disable address bar and back and forward button of browser - javascript

how can I disable or hide address bar and back and forward buttons in ie and firefox
i tried lots of links and solutions but non of them worked
for example for disabling back button:
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
but it seems that it goes to previous page then it returns
and i trid :
window.scrollTo(0, 0); // reset in case prev not scrolled
var nPageH = $(document).height();
var nViewH = window.outerHeight;
if (nViewH > nPageH) {
nViewH -= 250;
$('BODY').css('height', nViewH + 'px');
}
window.scrollTo(0, 1);
}
for disabling menu bar but it didnt work
what can i do

Instead of disabling the back button, try to make your page that supports users to going back. It will increase the usability of your application.
Even you can impliment it for the ajax activities also.

Don't think you can disable buttons on browser. I mean, otherwise, we'd seen it on spyware infected sites...
In terms of hiding them, I've seen banks use a full screen popup without those buttons (but hardware button on mouse or hitting backspace still works).

Not tested but you can bind to the window's hashchange event.
For example, in jQuery it very easy to do:
$(window).bind('hashchange', function(e)
{
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false; // stop event
});
The result is that the back button not changes the page when an anchor is in the url. But i agree with the first answer also (it is not a real answer i think, it is an advice).
You can also override the last entry in window.history, so user can't go back.

Related

When hash is added on url, scroll stops working on mozilla firefox [duplicate]

I have a sliding panel set up on my website.
When it finished animating, I set the hash like so
function() {
window.location.hash = id;
}
(this is a callback, and the id is assigned earlier).
This works good, to allow the user to bookmark the panel, and also for the non JavaScript version to work.
However, when I update the hash, the browser jumps to the location. I guess this is expected behaviour.
My question is: how can I prevent this? I.e. how can I change the window's hash, but not have the browser scroll to the element if the hash exists? Some sort of event.preventDefault() sort of thing?
I'm using jQuery 1.4 and the scrollTo plugin.
Many thanks!
Update
Here is the code that changes the panel.
$('#something a').click(function(event) {
event.preventDefault();
var link = $(this);
var id = link[0].hash;
$('#slider').scrollTo(id, 800, {
onAfter: function() {
link.parents('li').siblings().removeClass('active');
link.parent().addClass('active');
window.location.hash = id;
}
});
});
There is a workaround by using the history API on modern browsers with fallback on old ones:
if(history.pushState) {
history.pushState(null, null, '#myhash');
}
else {
location.hash = '#myhash';
}
Credit goes to Lea Verou
The problem is you are setting the window.location.hash to an element's ID attribute. It is the expected behavior for the browser to jump to that element, regardless of whether you "preventDefault()" or not.
One way to get around this is to prefix the hash with an arbitrary value like so:
window.location.hash = 'panel-' + id.replace('#', '');
Then, all you need to do is to check for the prefixed hash on page load. As an added bonus, you can even smooth scroll to it since you are now in control of the hash value...
$(function(){
var h = window.location.hash.replace('panel-', '');
if (h) {
$('#slider').scrollTo(h, 800);
}
});
If you need this to work at all times (and not just on the initial page load), you can use a function to monitor changes to the hash value and jump to the correct element on-the-fly:
var foundHash;
setInterval(function() {
var h = window.location.hash.replace('panel-', '');
if (h && h !== foundHash) {
$('#slider').scrollTo(h, 800);
foundHash = h;
}
}, 100);
Cheap and nasty solution.. Use the ugly #! style.
To set it:
window.location.hash = '#!' + id;
To read it:
id = window.location.hash.replace(/^#!/, '');
Since it doesn't match and anchor or id in the page, it won't jump.
Why dont you get the current scroll position, put it in a variable then assign the hash and put the page scroll back to where it was:
var yScroll=document.body.scrollTop;
window.location.hash = id;
document.body.scrollTop=yScroll;
this should work
I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:
if (history.pushState) {
// IE10, Firefox, Chrome, etc.
window.history.pushState(null, null, '#' + id);
} else {
// IE9, IE8, etc
window.location.hash = '#!' + id;
}
As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:
id = window.location.hash.replace(/^#!?/, '');
Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.
This solution worked for me.
The problem with setting location.hash is that the page will jump to that id if it's found on the page.
The problem with window.history.pushState is that it adds an entry to the history for each tab the user clicks. Then when the user clicks the back button, they go to the previous tab. (this may or may not be what you want. it was not what I wanted).
For me, replaceState was the better option in that it only replaces the current history, so when the user clicks the back button, they go to the previous page.
$('#tab-selector').tabs({
activate: function(e, ui) {
window.history.replaceState(null, null, ui.newPanel.selector);
}
});
Check out the History API docs on MDN.
This solution worked for me
// store the currently selected tab in the hash value
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
And my full js code is
$('#myTab a').click(function(e) {
e.preventDefault();
$(this).tab('show');
});
// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
var id = $(e.target).attr("href").substr(1);
if(history.pushState) {
window.history.pushState(null, null, '#' + id);
}
else {
window.location.hash = id;
}
// window.location.hash = '#!' + id;
});
// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
// console.log(hash);
$('#myTab a[href="' + hash + '"]').tab('show');
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
When using laravel framework, I had some issues with using a route->back() function since it erased my hash. In order to keep my hash, I created a simple function:
$(function() {
if (localStorage.getItem("hash") ){
location.hash = localStorage.getItem("hash");
}
});
and I set it in my other JS function like this:
localStorage.setItem("hash", myvalue);
You can name your local storage values any way you like; mine named hash.
Therefore, if the hash is set on PAGE1 and then you navigate to PAGE2; the hash will be recreated on PAGE1 when you click Back on PAGE2.

Hashchange history breaks iScroll

I have created the following application using iScroll: http://preview.na-software.co.uk/Demo/FutureLearning4/#/section-0
As the user flicks left and right or clicks the arrows in the bottom corners, the application moves the content sections it updates the history by changing the hash so that the user can move back and forth to other sections and bookmark them etc.
However! If you access a hash like: http://preview.na-software.co.uk/Demo/FutureLearning4/#/section-2 and then navigate a few sections and then use the back buttons two issues happen:
1.) It scrolls to the first screen (even though currentSection is correct, and iScroll has been told the correct section).
2.) If you click the back or forward button multiple times, you stop the animation and cause it to become confused and stick in between two sections.
Looking into the code, and seeing that the correct indexes and elements are being passed to iScroll on hashchange, and console logging out the offsets, I've discovered the issue is cause because the offsets are incorrectly set... however just doing refresh() won't fix the issue, as it will then reset the position.
Can anyone see where the problem is or see a way to fix this?
I should note that this bug ONLY happens if you come into the application on a URL that isn't section 0 and then scroll around the application. This is because the offsets will be created correctly by your interactions. But if you come into a URL like section 3, then the offsets will be incorrect and so the hashchanges don't work correctly, if that makes sense.
The hashchange method looks like:
// handle hashchange events
$(window).hashchange( function(){
// read the hash to find out what the new section number is
var nums = location.href.match(/(section)-\d+/g).map(
function(x){ return +x.replace(/\D/g,"") }
);
// set currentSection
currentSection = nums[0];
// if the hashchange was called by user scrolling
if(hashCalledByScroll){
// no need to anything as they have already updated hash and scrolled
hashCalledByScroll = false;
} else {
// find the section to scrollTo
sectionToScrollTo = $('#horizontal > .sections > .section').eq(currentSection).attr('id');
// tell iscroll to scroll to the section
horizontal.scrollToElement( '#' + sectionToScrollTo, null, null, true );
}
// hide the menu on hashchange
hideMenu();
});
Testing your site, I noticed the following: Whenever I access the site via section-3 and then enter the url for section-2, the navigation would instead send me to section-0.
I believe this is the same behaviour as you are experiencing in 1).
So I investigated and came to the following analysis:
In the function horizontal.scrollToElement( '#' + sectionToScrollTo, null, null, true )
iScroll retrieves the utils.offset(el) [iScroll.js#772] for the given el-ement. This offset tells it, where the element to scroll to is.
iScroll goes through the element and all of its offsetParents to add up their offsets. This is where things are breaking: <div class="sections"> has a negative offset to its parent, which imho it should not have.
This, in turn, messes up the scrollTo-coordinates.
To see what I am talking about: document.querySelector('.sections').offsetLeft
This has all just been analysis. My approach to fix this would be to avoid scrollToElement() and instead use scrollTo():
...
} else {
// find the section to scrollTo
sectionToScrollTo = $('#horizontal > .sections > .section').eq(currentSection).attr('id');
// tell iscroll to scroll to the section
var posLeft = -$('#' + sectionToScrollTo)[0].offsetLeft;
var posTop = -$('#' + sectionToScrollTo)[0].offsetTop;
horizontal.scrollTo(posLeft, posTop, 1000);
}
// hide the menu on hashchange
hideMenu();
});
Thus, just calculate the location of the section you want to go to yourself.
About 2) I am not sure if there is much one can do about it. Jumping around quickly breaks a lot of carousels. Maybe a delayed callback to scrollEnd, verifying the validity of the current state.
Another thing I noticed is that you can accidentally stop the transition. Try to click, hold and release the cursor midway a transition - you need to be quick.
Hope this helps.
Found not best solution and it doesn't solve main problem, but it works.
$(window).hashchange(function () {
if (hashCalledByScroll) {
hashCalledByScroll = false;
} else {
var hpage = window.location.hash;
var hpage = hpage.replace('#/section-', ''); //get number of target page
var cpage = currentSection; //number of current page
var count = parseInt(hpage) - parseInt(cpage); //difference
while (count > 0) { //if difference positive: go forward count-times
horizontal.next();
count--;
}
while (count < 0) { //if difference negative: go backward count-times
horizontal.prev();
count++;
}
}
hideMenu();
});
FIDDLE

Change location.hash on unbeforeunload

I have a page which is generated using JavaScript. I want to store the $(window).scrollTop() value in a hash (like #position=xxx) so when the page is refreshed and the items are generated again, the user can continue scrolling from where they left off.
I'm trying to modify the hash on beforeunload, which does not seem to work. The first part of the function below tries to change the hash, and the second part is taking care of the modification of the scrollTop on page load. The second part works fine, I'm only stuck with the first part.
$(window).on('beforeunload',function(){
window.location.hash = "position="+$(window).scrollTop();
}).on('load hashchange',function(){
var scrollregex = /^position=(\d+)$/,
hash = window.location.hash.substring(1);
if (scrollregex.test(hash)) $(window).scrollTop(parseInt(hash.match(scrollregex)[1]));
});
Is there a different event for this, or otherwise how can I change the hash when the user triggers a refresh?
I ended up ditching the hash idea and going with a sessionStorage based approach. I wrote my own wrapper for session/local storage which I use in the following example.
$(window).on('beforeunload',function(){
var scrltop = $(window).scrollTop();
if (scrltop > 0) SStorage.set('position',scrltop);
else SStorage.del('position');
}).on('load',function(){
if (SStorage.has('position')){
var pos = parseInt(SStorage.get('position'));
if (!isNaN(pos) && $(window).scrollTop() === 0) $(window).scrollTop(pos);
}
});
Chrome doesn't seem to allow you to update the hash in the onbeforeunload event. I had a similar issue. I moved my code to the unload event, which worked but introduced other issues. To solve them I have to force a reload, note reload will not work without the setTimeout.
$(window).on('unload', function(){
/* Do hash change here */
setTimeout(function () { window.location.reload(true); }, 0);
});

HTML scrolls simultaneously in page and Flash object

I have a flash object inside a div, that will zoom it's content when I scroll over it. the problem is that my page also scrolls and I don't know how to fix this problem. I need the page to stand still when I scroll over the flash.
I tried adding this
flashContainer.bind('mousewheel DOMMouseScroll', function(e) {
var scrollTo = null;
if (e.type === 'mousewheel') {
scrollTo = (e.originalEvent.wheelDelta * -1);
} else if (e.type === 'DOMMouseScroll') {
scrollTo = 40 * e.originalEvent.detail;
}
if (scrollTo) {
e.preventDefault();
$(this).scrollTop(scrollTo + $(this).scrollTop());
}
});
but because of preventDefault, the flash object won't zoom anymore.
Do you have any suggestions?
may be this could work for you:
$("element").hover(function(){
var scrollT = $(document).scrollTop();
$(document).on("scroll", function(e){
$(document).scrollTop(scrollT);
});
}, function(){
$(document).off("scroll");
});
http://jsfiddle.net/ZFsDY/3/
I stumbled on this issue a few months ago (the old method we used to manage scrolling didn't work on the most recent browsers).
I'm not allowed to publish the code for it, but here a few note on how we did it.
Like in reyaner's answer, we use event listening and preventDefault() to disable the browser auto scrolling, and get the scroll value (but without scrollTop()).
Once we have the value, we send it to the Flash via ExternalInterface.
For it to be possible, the flash object must beforehand add a Callback, a Flash method that can be called by Javascript.
We added a couple of additional interaction between Flash and JS so that the scroll is locked only when the Flash has the focus.
A warning : all browser don't have the same scale for the wheelDelta, and you may find that the zoom speed can vary. To fix this we decided to always use a fixed step each time the event is dispatched, instead that using the delta as-is.
another try:
$("element").bind( 'mousewheel DOMMouseScroll', function ( e ) {
var d = e.wheelDelta || -e.detail;
var s;
if(d < 0) s = 1;
else s = -1;
this.scrollTop += s * 30;
e.preventDefault();
});
http://jsfiddle.net/ZFsDY/5/

How to detect when a tab is focused or not in Chrome with Javascript?

I need to know if the user is currently viewing a tab or not in Google Chrome. I tried to use the events blur and focus binded to the window, but only the blur seems to be working correctly.
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
The focus event works weird, only sometimes. If I switch to another tab and back, focus event won't activate. But if I click on the address bar and then back on the page, it will. Or if I switch to another program and then back to Chrome it will activate if the tab is currently focused.
2015 update: The new HTML5 way with visibility API (taken from Blowsie's comment):
document.addEventListener('visibilitychange', function(){
document.title = document.hidden; // change tab text for demo
})
The code the original poster gives (in the question) now works, as of 2011:
window.addEventListener('focus', function() {
document.title = 'focused';
});
window.addEventListener('blur', function() {
document.title = 'not focused';
});
edit: As of a few months later in Chrome 14, this will still work, but the user must have interacted with the page by clicking anywhere in the window at least once. Merely scrolling and such is insufficient to make this work. Doing window.focus() does not make this work automatically either. If anyone knows of a workaround, please mention.
The selected answer for the question Is there a way to detect if a browser window is not currently active? should work. It utilizes the Page Visibility API drafted by the W3C on 2011-06-02.
It might work after all, i got curious and wrote this code:
...
setInterval ( updateSize, 500 );
function updateSize(){
if(window.outerHeight == window.innerHeight){
document.title = 'not focused';
} else {
document.title = 'focused';
}
document.getElementById("arthur").innerHTML = window.outerHeight + " - " + window.innerHeight;
}
...
<div id="arthur">
dent
</div>
This code does precisly what you want, but on an ugly way. The thing is, Chrome seems to ignore the title change from time to time (when switching to the tab and holding the mouse down for 1 sec seems to always create this effect).
You will get different values on your screen, yet your title won't change.
conclusion:
Whatever you are doing, don't trust the result when testing it!
For anyone who wants to swap page titles on blur and then go back to the original page title on focus:
// Swapping page titles on blur
var originalPageTitle = document.title;
window.addEventListener('blur', function(){
document.title = 'Don\'t forget to read this...';
});
window.addEventListener('focus', function(){
document.title = originalPageTitle;
});
I found that adding onblur= and onfocus= events to inline bypassed the issue:
This could work with JQuery
$(function() {
$(window).focus(function() {
console.log('Focus');
});
$(window).blur(function() {
console.log('Blur');
});
});
In chrome you can run a background script with a timeout of less than 1 second, and when the tab does not have focus chrome will only run it every second. Example;
This doesn't work in Firefox or Opera. Don't know about other browsers, but I doubt it works there too.
var currentDate = new Date();
var a = currentDate.getTime();
function test() {
var currentDate = new Date();
var b = currentDate.getTime();
var c = b - a;
if (c > 900) {
//Tab does not have focus.
} else {
//It does
}
a = b;
setTimeout("test()",800);
}
setTimeout("test()",1);

Categories