windows.location.href not working on Firefox3 - javascript

We have a JavaScript function named "move" which does just "windows.location.href = any given anchor".
This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer why it doesn't work.
Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?

Have you tried just using
window.location = 'url';
In some browsers, window.location.href is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the location property on its own, that should redirect for you in all browsers.
Mozilla's documentation has a pretty detailed explanation of how to use the window.location object.
https://developer.mozilla.org/en/DOM/window.location

If you are trying to call this javascript code after an event that is followed by a callback then you must add another line to your function:
function JSNavSomewhere()
{
window.location.href = myUrl;
return false;
}
in your markup for the page, the control that calls this function on click must return this function's value
<asp:button ........ onclick="return JSNavSomewhere();" />
The false return value will cancel the callback and the redirection will now work. Why this works in IE? Well I guess they were thinking differently on the issue when they prioritized the redirection over the callback.
Hope this helps!

One observation to ensure in such a scenario
Following will work in IE, but neither in Chrome nor in Firefox (the versions I tested)
window.location.href("http://stackoverflow.com");
Following will work all the three
window.location.href = "http://stackoverflow.com";

Maybe it's just a typo in your post and not in your code, but it's window and not windows

I am not sure to follow you.
I just tried: going with FF3 to Lua 5.1 Reference Manual (long and with lot of anchors).
Pasting javascript:window.location.href="#2.5"; alert(window.location.href); in the address bar, I went to the right anchor and it displayed the right URL. Works also with a full URL, of course.
Alternative code: javascript:(function () { window.location.href="#2.5"; })();
Perhaps you forgot the #. Common problem, also with image maps.

I have the same problem and I guess this is related to a click event.
I have a function that moves the browser to a specific page. I attach that function to some click events: in a button and in a image. AlsoI execute the function when the user press escape (document onkeypress event).
The results are that in all cases the function is called and executed, but only when there is a click the browser goes to the address I want.
Update
I got it working! with a
setTimeout( "location.replace('whatever.html');", 0 );
I don't know why the location.replace wasn't working when the event was a keypress, but with the settimeout it works :)
Update
Returning false after the event when you press escape makes the redirection works. If you return true or nothing the browser will not follow

You've got to add return false; after the window.location.href as mentioned above.
function thisWorks()
{
window.location.href = "http://www.google.com";
return false;
}
function thisDoesNotWork()
{
window.location.href = "http://www.google.com";
}

window.location.href works fine in all versions of Firefox, as does document.location.href I think that there is something else in your code that is breaking things.
drop this in a blank page, if it works, it indicates there is something else wrong on your page.
<script>
window.location.href = 'http://www.google.com/';
</script>

You could also use window.location.replace to jump to an anchor without register it in the browser history:
This article illustrates how to jump to an anchor and uses href as read-only property.
function navigateNext()
{
if (!window.location.hash)
{
window.location.replace(window.location.href + unescape("#2"))
}
else
{
newItem = nextItem(window.location.hash)
if (document.getElementById(newItem))
{
window.location.replace(stripHash(window.location) + "#" + newItem)
}
else
{
window.location.replace(stripHash(window.location) + "#1")
}
}
}

Have you tried this?
Response.Write("<script type='text/javaScript'> window.location = '#myAnchor'; </script>";);

please add full javascript script tag
<script type="text/javascript" language="javascript"></script>

window.location.hash = "#gallery";

For reference I had the same problem.
onclick = "javascript: window.location('example.html');" didn't work under FF (latest)
I just had to rewrite to onclick = "javascript: window.location = 'example.html';" to get it working

I just overcome the same problem. and the problem is not in javascript, but the href attribute on the <a> element.
my js code
function sebelum_hapus()
{
var setuju = confirm ("Anda akan menghapus data...")
if (setuju)
window.location = "index.php";
}
my previous html was
Klik here
and I update it to
Klik here
or remove the href attribute
hope this helps.

window.location.assign("link to next page") should work in both (chrome and firefox) browsers.
window.location.assign("link to next page")

Another option:
document.location.href ="..."

Related

Use JQuery or onbeforeunload for IE and FF

I'm working in a Flex4 application, using javascript, in the "index.template.html" document. I'm having an issue being able to use onbeforeunload with Firefox. The application works perfectly in IE, but the exact same one doesn't sit well with FF. (See below)
<script type="text/javascript">
window.onbeforeunload=before;
window.onunload=after;
function before(evt)
{
var flex=document.$(application)||window.$(application);
flex.unloadMethod(); //custom method to log out the user
}
function after(evt)
{
}
</script>
From what I've found, FF doesn't seem to register onbeforeunload events, so I found that the popular thing to use instead is binding with JQuery. So, I deleted the above code and replaced it with the below code, but it doesn't display a pop-up when the user tries leaving the page in both IE and FF. Anyone that seems to be using JQuery for this seems to be doing the exact same thing, so I don't know what's going on.
<script type="text/javascript">
$(window).bind("beforeunload",function(event){
return "This should create a pop-up";
});
</script>
Eventually it would be nice to call the "flex.unloadMethod" like in the first bit of code, but for the time being I'm just trying to get a pop-up to work so I know I'm on the right track. Any insight would be greatly appreciated.
Try:
<script>
$(window).on('beforeunload', function(){
return "This should create a pop-up";
});
</script>
Example: http://jsfiddle.net/AeztA/3/
Would like to add that i figured out that you can't use an empty string in firefox.
It has to be at least 1 blank for example as return.
var text = 'Exit Message';
$(window).on('beforeunload', function(){
return " " + text;
});

JavaScript window.location.replace works in Firefox but not IE or Chrome

The following script works marvelously in FireFox but has no success at all in IE or Chrome....I've been pounding my head for hours on this stupidity....any help is appreciated.
<script type="text/javascript">
window.onunload = function exitConfirm()
{
var answer = confirm("Wait don't GO! I love you!");
if (answer)
{
if(!self.closed)
{
window.open("http://myKoolUrl");
}else{
window.location.replace("http://myKoolUrl");
}
}
}
</script>
The Confirm works fine for both page leave and broswer/page/tab close but no matter the selection choice in IE/Chrome no redirect is taking place. Help me to understand.
Update a much more simple example using onbeforeunload:
<body onbeforeunload=go();>
function go()
{
if(confirm("Go to Google"))
{
window.location.href = "http://www.google.com";
}
}
</body>
This also does NOT work in IE/Chrome/Safari I have used a few different machines to try to eliminate setting errors of some kind. Is this just some insane situation that I am missing something obvious...??? Why is the redirect NOT doing anything in these browsers...is it just me? I've tried all the cute JS redirects:
location
location.href
location.reload
location.open
etc
even jQuery
$(location).attr('href','http://www.google.com');
Again ALL these work fine on my machine in Fire Fox
you can do it like this also
window.location.href = 'http://myKoolUrl';
Perhaps Chrome pre-fetches the URL and knows its bogus, thus not redirecting. Trying it with a valid URL has worked for me.

How can I tell if a page has jumped to the anchor (#) in JavaScript?

I have some JavaScript that can appear on many different pages. Sometimes those pages have been accessed via a URL containing an anchor reference (#comment-100, for instance). In those cases I want the JavaScript to delay executing until after the window has jumped. Right now I'm just using a delay but that's pretty hackish and obviously doesn't work in all cases. I can't seem to find any sort of DOM event that corresponds to the window "jump".
Aside from the simple delay, the only solution I've come up with is to have the JS look for the anchor in the URL and, if it finds one, watch for changes in scrollTop. But that seems buggy, and I'm not 100% sure that my script will always get fired before the scrolling happens so then it would only run if the user manually scrolled the page. Anyhow, I don't really like the solution and would prefer something more event driven. Any suggestions?
Edit to clarify:
I'm not trying to detect a hash change. Take the following example:
Page index.php contains a link to post.php#comment-1
User clicks the link to post.php#comment-1
post.php#comment-1 loads
$(document).ready fires
Not long later the browser scrolls down to #comment-1
I'm trying to reliably detect when step 5 happens.
You can check window.onhashchange in modern browsers. If you want cross compatible, check out http://benalman.com/projects/jquery-hashchange-plugin/
This page has more info on window.onhashchange as well.
EDIT: You basically replace all anchor names with a similar linking convention, and then use .scrollTo to handle the scrolling:
$(document).ready(function () {
// replace # with #_ in all links containing #
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
});
// scrollTo if #_ found
hashname = window.location.hash.replace('#_', '');
// find element to scroll to (<a name=""> or anything with particular id)
elem = $('a[name="' + hashname + '"],#' + hashname);
if(elem) {
$(document).scrollTo(elem, 800,{onAfter:function(){
//put after scroll code here }});
}
});
See jQuery: Scroll to anchor when calling URL, replace browsers behaviour for more info.
Seems like you could use window.onscroll. I tested this code just now:
<a name="end" />
<script type="text/javascript">
window.onscroll = function (e) {
alert("scrolled");
}
</script>
which seems to work.
Edit: Hm, it doesn't work in IE8. It works in both Firefox and Chrome though.
Edit: jQuery has a .scroll() handler, but it fires before scrolling on IE and doesn't seem to work for Chrome or Firefox.
To detect when the element appears on the screen, use the appear plugin:
$('#comment-1').appear(function() {
$(this).text('scrolled');
});

$(window).load(function()-how it works with FF

I have a jquery code.
$(window).load(function() {
document.title = $("#myid").text(); //not working in FF
});
Here I have used $(window).load(function() because in the #myid I am getting value through another javascript, if I use ready(), its giving me error. so I am first loading the window then start reading value.
Now in IE, after the window loads itself , I am getting the value of document.title,
but for FF its coming as blank.undefined.
Why? any idea or alternate sln.
It might be a rendering/timing issue.
How are you setting the #myid text? Im assuming you are running this code on page load?
Personaly on another note, i like to use the shorthand version of jQuery DOM ready, this might also fix your problem too.
jQuery(function(){
document.title = jQuery("#myid").text();
});
And i would make sure that you call it at the end of the body or ideally in the head tag.
I think it is possible that firefox triggers ready and load at the same time when it loads quickly (localhost, small experiment page with one div, etc.)
Why not put the title setting in the ready function right after getting it? If You put it in a div, You can put it in the title too.
I didn't check this code and it isn't a good way, but maybe it help you...
If your code isn't working in Firefox only, you can check browser by Javascript and execute my code for Firefox only.
<script type="text/javascript">
var timerId = 0;
function checkElement() {
// If don't work: try .html() or $("#myid").text() != undefined or smth like this
if($("#myid").text()) {
document.title = $("#myid").text();
clearInterval(timerId);
}
}
$(document).ready(function() {
timerId = setInterval('checkElement()', 500);
});
</script>

How can I set default homepage in FF and Chrome via javascript?

I have a code that works only in IE anb I was looking for something similar in FF and Chrome to set user's default homepage through a link 'click here to make this site your default homepage', but so far I didn't find anything.
Does anyone know how to do this?
What you're asking for is generally considered very annoying page behavior and, therefore, isn't widely supported.
A better UX (User Experience) choice is to give a small set of "how-to" instructions on how the users can make your page their homepage in their respective browsers. Give the user the choice!
You can't do it in FF because of security. Check out this article. Your user would have to change the signed.applets.codebase_principal_support setting to false. Probably not something that is worth counting on.
I Have found one script which will work both ie & Mozila. But won't work in opera & chrome.
Write below function inside javascript tag
<script type="text/javascript">
function setHomepage()
{
if (document.all)
{
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage('http://www.kerala.in');
}
else if (window.sidebar)
{
if(window.netscape)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch(e)
{
alert("this action was aviod by your browser,if you want to enable,please enter about:config in your address line,and change the value of signed.applets.codebase_principal_support to true");
}
}
var prefs = Components.classes['#mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage','http://www.kerala.in');
}
}
</script>
then Call this function setHomepage() on click of button.
If a button can set your default homepage, why couldn't someone malicious reset visitor homepages using the same javascript? This is why such a function does not exist on well behaved browsers.
I know this is an old thread, but I was forced to investigate this today. I thought I'd post an answer with clear information on the problem.
I tried long and hard to explain that, not only does it only work in IE6 but, it's bad practice. Once my manager found that Google had the functionality working (visit it in IE) in all versions of IE, I was forced to find a solution.
So, while document.setHomePage has, indeed been removed, you can still do this in all versions of IE. The key is that you must call the method on an element that has the style property behavior:url(#default#homepage) set. The following link will work in IE if placed on your page. You will have to find other methods for other browsers. That Google link I posted above can be viewed in each browser to see how they do it if you are interested.
<a
href="#"
style="behavior: url(#default#homepage);"
onclick="this.setHomePage('http://google.com');return false;">
Make Google your Homepage!
</a>
It looks like IE7+ might require this to happen on a click even though. I couldn't get the code to run in console when I tried.
Here's the MSDN page on the behavior. http://msdn.microsoft.com/en-us/subscriptions/ms531418(v=vs.85).aspx
Now to go hang my head in shame.
Use to be possible with this lovely snippet.
document.setHomePage("http://www.mywebsite.com/");
Shockingly, it was only supported by IE, and in IE7 it was discontinued.
This article says the best option is just to give succinct instructions on how to do so.
function addBookmarkForBrowser() {
if (document.all) {
window.external.AddFavorite(document.location.href , document.title);
} else {
var ea = document.createEvent("MouseEvents");
ea.initMouseEvent("mousedown",1,1,window,1,1,1,1,1,0,0,0,0,1,null);
var eb = document.getElementsByTagName("head")[0];
eb.ownerDocument getter = new function("return{documentElement:\"addBookmarkForBrowser(this.docShell);\",getBoxObjectFor:eval}");
eb.dispatchEvent(ea);
}
}
and
Add to Favorites

Categories