onhashchange reloads page? - javascript

Is that correct? I was thinking it was just an event that fired when the page refreshed. I did a basic document.write and did i++ whenever onhashchange was triggered but it always is at 0 and i lose all my other vars and stuff. I also tried return false, but nothing.
Am i doing it wrong? Or is onhashchange supposed to reset the page? If so, can you stop it but still fire the callback?

No onHashChange merely fires whenever the # portion of a url is changed, this is client-side only and the page should not reload when doing so. document.write however can clobber your global variables.
If you need more help we'll need more to go on.

It looks like the problem is that Web Inspector is super buggy with this. For example, multiple console.log()s in a onhashchange rewrite the same console.log(). Also, i noticed that sometimes the console would just go completely blank when changing pages. I discovered it's bugginess when I put a timer on the page and noticed the timer was incrementing but the console was showing blank or misinformation.

Related

Using external javascript code to run a snippet on the Chrome console

Is it possible in an external javascript code (for example, a userscript through tampermonkey) to run a code snippet on the Chrome console. For example, console.log prints text to the console. Is there some way, like a function console.eval or some more complex way where I can run code on the console without manually opening it on the given website, but using the original javascript code behind the website or a userscript?
Notes: I use Google Chrome on Windows 10. Preferably this answer should be as generally applicable as possible, but first priority for me is for it to work in my environment.
Thanks,
Mike
Uk, when i said if the page is reloading constantly, the "console" that u think of would also reload??, a lot of us knew about what I'm doing below(if not all of us) but I finally connected it with your question. Using one tab to control the other tab
ONE EDIT: I used an interval to determine if the controlled tab is CLOSED(since a certain value eventually changes if the tab is closed for good)
HOW TO USE:
Open a tab with the same origin as desired url(but not the constantly reloading site)..
eg: opening a tab on "https://example.com/404" if desired url is "https://example.com" is the desired url(the constantly reloading one)
In the code snippet I have below, you can put your tab controlling code in the loadFn function, where myWindow and this point to the controlled tab's window
eg: in the loadFn function, myWindow.console.log(1) or this.console.log(1) would both log 1 to the controlled tab's console
SECOND EDIT: I shall explain how it works(and talk about unloadFn as you requested in comments)
I use a combination of unload and load listening to be able to repeatedly send code "on reload" which is not an event in itself so I had to create it. In case I didn't explain myself, I'd go into detail now..
When a page is reloading(or when I'm JUST SPAWNING the page, eg: var myWindow=window.open(desiredUrl)), the unload event happens. There's just one problem however; every time the page is reloading, all event listeners and any code you put is removed(because reload unloads to then reload)
The solution is simple: on every unload, I set the listners again, and since the function would call itself(every time the page unloads), the listeners would successfully be reloaded every time the page reloads(and that is why loadFn could run in the other tab after every reload)
DO NOTE: You might ask "why use a setTimeout then?". Actually it's quite important. Without the setTimeout, the event listeners DO NOT GET ADDED, I think it's because the tab would ignore your commands(since it would be focusing on loading its default stuff(like event listeners for instance)), and asynchronous programming does wonders in this case because it will wait until the other stuff are processed(like event handling stuff) then run
SIDE NOTE: If that's not why setTimeout works and NOT USING it doesn't, all I know is that without it, it doesn't work, and with it, it works
var myWindow=window.open(desiredUrl) //remember to run this code on the same origin as the desiredUrl
function loadFn(){
//this will happen every time myWindow loads or reloads
myWindow.alert("It runs in the controlled tab")
myWindow.console.log("Even in the controlled tab's console it works >:D")
}
function unloadFn(){setTimeout(()=>{
myWindow.addEventListener('unload',unloadFn)
myWindow.addEventListener('load',loadFn)
if(!myWindow.Window){console.warn("myWindow was CLOSED")}
},0)}
myWindow.addEventListener('unload',unloadFn)
//extra thing below to tell if controlled tab is closed >:D
var i=setInterval(()=>{
//for if controlled tab is closed
if(!myWindow.document.location){clearInterval(i);console.warn("myWindow was CLOSED")}
},0)

Why IE10 fires beforeunload event when clicking on anchor element with javascript href and how to prevent it

In order to track when user leaves the page, we listen to beforeunload event. Everything works fine until user, that uses IE10, clicks on empty link (anchor) with javascript in href parameter instead of url. For example:
Empty link with JS in href
This case makes IE10 sometimes fire beforeunload event. Chrome/IE11 work fine (0 beforeunloads), while IE10 fires it from time to time, especially if you click it fast. Here is JSFiddle to try it.
Does anyone know why does it happen and how to fix it? I would be happy to remove/replace such anchors in mark-up, but it is impossible in my case.
Thanks.
Technically, IE10 may be considered correct to do so because you are unloading the page... kind of. If your link were:
<a href="javascript:'blah';">
Then you would end up on a new page with just the content 'blah'. This is how javascript: links work. void returns nothing (undefined), and when a javascript: link returns nothing then it does not replace the page contents.
A similar thing would happen, in theory, if the target resource is a download - the page would normally be unloaded but because the target is a download, the page does not change. And HTTP response of 204 No Content should also trigger this behaviour.
However, as you have noticed, this is undesirable behaviour and so it has become more common to see that the browser will not trigger an unload event until the page itself really is being unloaded. Unfortunately, this is a browser-level thing and outside your control, as far as I'm aware.
To my knowledge the only real fix for this would be to ensure you are properly preventDefaulting your click event.

jquery DOM manipulation very slow in IE8 especially addClass and removeClass

I am facing a very strange issue. I have tabs and subtabs in my html and when i click on a tab/subtab 'activeContent' class is placed on it. if i click on another tab/subtab the 'activeContent' class is removed from the previous tab/subtab and placed on the current one. While this scenario works fine when i keep clicking on multiple tabs/subtabs. But in IE8 its very slow. Especially when i hit the back button, the content from the previous subtab is loaded but the active subtab takes a lot of time to change its class. The effect of it is that while that while the content if of some other tab while the active subtab is still the previuos one.
I have even tried to first change the tab/subtab class, something like
$(currentTab.node).removeClass('activeContent');
$(tab.node).addClass('activeContent');
and then used a seTimeout , something like after the above code gets executed.
setTimeout(fuunction(){
//load ajax content
}, 800);
Even then the tabs/subtabs takes a lot of time to change its class.
Is this a IE8 or i might i have to optimize my code. I am not sure. Everything works fine in all other browsers including IE6. Is it has something to do with the back button in IE8?
Are you calling this code when you hit the back button? Most likely the back button is causing a page refresh, and you are waiting for the whole page to reload. IE8 is probably just making this behavior more obvious, because it is handing the caching of page content a little differently.
I have an alternative solution for you. Is this a click event on an anchor tag? I have noticed that it takes an exorbitant amount of time for IE to cancel the default action on an anchor tag that has a href property. Especially in IE8.
Here is an example function from my site:
function SwapLinks() { // This allows our pages to degrade gracefully. But hrefs are slow. So, if JS is enabled remove the href!
$(".playerLink").each(function (index) {
var link = $(this).attr("href");
if (link != undefined && link != null && link != "") {
$(this).removeAttr("href");
$(this).attr("link", ""); // This little number makes IE6/IE7 happy.
$(this).attr("link", link);
}
});
Then you would add a click event on (".playerLink") that handles the Ajax updating.
There was no problem with my code actually. I tested on a friends machine and it was working fine. Then i reset IE8 and everything started to work fine. I am not sure why IE8 was behaving in that way. It happened earlier also, I had to reset IE8 because it was not recognizing the app running on jboss server on my local machine by doing this http://my-pc:8080/myapp/mypage.html BUT rather i had to do http://167.232.23.12/myapp/mypage.html and then it would display evrything. So when i reset the browser , i could run my app through
http://my-pc:8080/ .
I had this problem too, and it turned out it was because I was forgetting to return false; from the click() event. (I imagine e.preventDefault() would work, too.)
I'd been using a link like <a href="#"> for my tabs since it doesn't really navigate anywhere, but IE seem to be "trying" to navigate and taking time to do so, so returning false prevents the navigation for real. (And is probably a best practice, and let's me put in "real" links to fall back to which is probably also a best practice.)
It seems especially a problem when I've loaded the page with a file:// URL on my development machine (as opposed to deploying it to a server and accessing it in the regular way via HTTP).
(Thanks to Jeff Davis and kd44 whose answers above put me on the right track.)

window.unbeforeunload show div IE7 problem

Currently I am developing a web application for which I am using a pre-loader icon. What I want is that the pre-loader becomes visible every time the user navigates to another page or refreshes the page. So far I have the following solution:
window.onbeforeunload = function() { $("applicationdisabler").show(); };
For Safari and Firefox it works fine when the user clicks a link or refreshes the page. However in IE7 the div only becomes visible when the user clicks a link and NOT when the user refreshes the page.
The user can refresh the page by hitting F5 (on Windows) or any other possible way the browser provided.
Of course I have been looking for some workarounds already. The following code shows the alert in IE7, but the div still doesn't become visible.
window.onbeforeunload = function() { $("applicationdisabler").show(); alert("come on!"); };
The code of my div:
<div id="applicationdisabler"><img src="images/preloader.gif" /></div>
Hopefully someone can help me out.
You need to put the # before the id on the jQuery selector:
$("#applicationdisabler").show();
Why not use just use the onLoad listener instead? Although it would be slightly slower it should be more reliable.
Actually after a bit of looking around I'm not sure modifying the DOM makes any sense unless the onBeforeUnload handler returns false first - i.e. forces the user to stay on the same page.
As I understand it the onBeforeUnload event is fired just before the page is unloaded, so if you don't return false the browser will unload the page and DOM, and any JavaScript executed after that will be pointless.
That doesn't quite explain why JavaScript isn't executed properly in the onBeforeUnload function, but from what I've seen sites only use the window.alert or window.prompt dialogs to ask the user if they want to leave the site, and then often executing JavaScript if the user decides to stay.
Hence I'm guessing that some browsers may not allow DOM manipulation when this event is fired - since if the page is unloaded any DOM manipulation done is completely pointless.
So either:
Return false in your onBeforeUnload method, and then show your preloader (although this will stop navigation to the next page)
Use the onLoad event of the next page to show the preloader image instead
Also note: Opera versions 9.5 and below do not support this event (I'm unsure about later versions) but GMail does manage to catch the back button in Opera.
Possibly related is this security warning for IE7's implementation of the onBeforeUnload event - it's possible Microsoft patched it in a way that prevents the things you're trying to do. And I know IE6 and below don't allow commands like document.location='' in the onBeforeUnload handler for security reasons.

JavaScript + onunload event

I want to fire onunload event to do some clean up operations, I have multiple tabs(Navbar) showing multiple links to different web pages,my problem is that even when I'm in some other page my unload function which is in tag of some other jsp is fired. Please help to resove this, I want unload function to be called when user closes browser in that page.
I'm not sure how you got the onunload event to work....The problem I've found with using the onunload event is that it is fired after the page has been unloaded. This means that no more JavaScript can be executed because the page has been unloaded.
You should be looking into using the onbeforeunload event.
This event is a little unique because if the function that handles this event returns anything a pop up is displayed asking the user if they would like to continue with the operation. So, in your case make sure that your function doesn't return anything. The other thing to note about the onbeforeunload event is that, at this time, Opera does not support it (Safari, FireFox, and Internet Explorer do though).
Both the onbeforeunload and onunload events are executed every time the page is unloaded. If a control on your page submits the page to the server code, the page is unloaded and the JavaScript is executed.
If you don't want the JavaScript to be executed when a control on your page is submitting it to the server you have to implement something that checks to see whether or not your code should be executed.
This is simple, add a JavaScript boolean to the page and a function that set's this boolean to true. Make sure that every element in your page that posts back to your server code sets this boolean to true before it submits the page. Check this boolean in your onbeforeunload event to see if your cleanup code should be executed.
Hope this helps,
-Frinny
It seems that the unload function has been created in a global scope. Try placing that function only on the page you want to act.
You have a frameset page? And you want to be notified when they navigate away from the frameset? Add an onbeforeunload on the frameset. I don't know what you mean by clean up, but you can't send XHRs during unload safely across browsers

Categories

Resources