I am working a project. In the head section I have the following code in my head section so that the console is cleared every time I refresh the page.
Code:
window.onbeforeunload = function() {
console.clear();
};
The point of this is to make sure all errors, warnings, or messages are deleted (Safari doesn't delete console errors/warnings/messages when the page is refreshed.)
This should work, and it does, but it does not fire every time. Most of the time it does but about one out of ten times it doesn't.
Does anyone know why it is not firing every time?
Thank you.
Note: I could use window.addEventListener() instead of window.onbeforeunload but I chose not to.
Safari onbeforeunload is a bit buggy. Safari developers are working on fixing it, but for now, I would use a different browser.
Good luck!
Related
I'm seeing an odd bug in IE that I'm not seeing in Chrome. Specifically, this involves some JS code not firing when a (Telerik) wizard is navigated back to it's first step.
When the user clicks their "Previous" button, some data isn't being properly loaded. Hitting F12 and bringing up the developer console has shown me the following Warning:
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
Ok, so I go to the link provided and I noticed the documentation states:
In order to be cached, webpages must meet these conditions:
...
- The F12 Developer tools window isn't open
This is a problem, because when I use the navigation buttons within my wizard WHILE the dev window is open, it behaves properly, just as it does in Chrome.
How can I debug my related Javascript so I can figure out what's going on? Also, I understand what caching is but I'm not exactly sure what this is about and I have no idea why Chrome behaves differently. Is there a way that I can force IE to behave like chrome and cut on (or off) whatever features that are causing this issue?
Yuck. Back to old school debugging for you.
Short of putting the whole browser into a Windows debugger, you can pretty much forget about setting breakpoints. All you can do is log.
If you are lucky and your problem isn't too deep, you can use a sprinkling of simple alert() statements to let you know the state of things at various stages in your code. One nice thing is that you can serialize objects now pretty nicely; for example, you can do JSON.stringify(this), which will probably give you a giant output, which you can copy and paste into your IDE and unpack. A major upside to doing this is that the alert will block, so you can take your time studying the output. A major downside to this is that race conditions are now much more likely.
Alternatively, you can add a <textarea> to the page and throw your JSON.stringify(this) results into that. Because this means extra DOM mutations, it also increases the odds of race conditions, but not by much. (If race conditions are a possibility, you can do this:
(function () {
var currentState = JSON.stringify(this);
setTimeout(function () {
document.querySelector('textarea').value = currentState;
}, 1000);
})()
Even though these are now asynchronous, if you use this multiple times in sequence, these will execute in that same sequence (unless you change the timeout period).
If you are doing actual page navigations (and not just changing the URL with pushState()), then actually reading those logs is going to be a problem. The solution is to put the page in a frame and write the content out to a sibling frame. As long as both frames are running on the same domain, you will have no problem pushing the data into the sibling frame. If you can't put them on the same domain, you are kind of screwed.
I have a link that opens a new window using window.open. The pop up works fine, however the normal web page stops loading objects (images, scripts, ajax scripts) and sometimes the page doesn't load at all.
Here is my code:
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
Is there anything I am doing wrong?
Thanks,
Peter
First of all, please be more specific: tell us more about your browser and which version, and possible your OS. It could be more related to the browser than to the web content.
Then on to the possible problem; you start with saying "I have a link that ...".
To me that sound like you use <a href="javascript:DoSomething()">. Or perhaps <a href="#" onclick="DoSomething()">.
I tried both in some modern browsers: Chrome v37, IE v11. Both browsers did not produce what you describe:
- Chrome v37 will happily keep on loading, even if I immediately click a "window.open()"-link on top of a (huge) webpage;
- IE v11 will someshow show "false", which is strange, but still not what you got.
In some cases I also got to deal with the popup blocker.
A general tip might be to NOT USE <a href> for things like this. Behaviour seems inconsistent across browsers, also these days there are better alternatives, such as <span onclick="">...</span> and <button onclick="">...<button> or by using JQuery or other frameworks (which I do not know much about).
Although this many not be a conclusive answer, maybe this can help you experiment on your own, and think about possible causes or alternative ways of doing things.
The behaviour you describe should definitely NOT normally happen. This is confirmed by robbmj's JSFiddle, that fails to reproduce the problem. That's evidence that something is going on in the main page that is not plain vanilla page loading, or your "link opening" has something unusual to it. Apart from the syntax error (you use four parameters, not three).
Since you do not supply information on either of these points (how do you load the main page? How do you trigger the popup-opening code?), we do not even know if the problem
might be browser-related; I'd start and try to test things in IE, Chrome and Mozilla to see
whether anything changes; this might provide some useful insights.
One possibility
A very strong possibility is that your inadvertent fourth parameter goes into the window.open() "replace" parameter, which is a boolean, and triggers undefined behaviour or simply an error that stops everything. You should have things somewhat working in IE and not working at all in Firefox.
You should also be able to see whether this is the case by using Firefox and the Firebug extension, or the Web Developer Console in Chrome.
Another possibility
A more esoteric possibility is that the way you define the link might make the browser believe you've actually moved on to another page, so that there's no point in continuing loading the current page. Depending on the browser, this might have to do with how the link is defined and could be remedied by defining it some other way.
For example it could conceivably happen if you had
...
which I suspect is what led user Tomzan to ask, "is the link something like javascript:...?"
So if this is the case, try with this instead (this works for me in IE9/Chrome/FF):
link
function openPopup() {
MyWindow = window.open('player.php', 'Player', 'width=500, height=300');
// Also try the following. You won't probably like the results (it should send the
// popup window behind), but if it works, it proves we're dealing with a browser
// issue there.
// Blur and refocus
// MyWindow.blur();
// window.focus();
// Just focus
// window.focus();
return false;
}
Workaround
A possibly acceptable workaround could be to disable the link altogether (or hide it via CSS), and only reactivate/show it upon main document being ready. This sidesteps the problem, even if user experience could be somewhat worse due to a longer wait.
But if it's so likely that a user clicks on the link before waiting for the whole page to load, I'd also consider not automatically loading the rest of the page at all, and reorganize information to provide a more streamlined navigation. Or maybe distribute it on two sequential pages. Again, unfortunately you did not supply enough information to do more than guess.
As you probably know, JavaScript is single threaded. Every event is queued until there is idle time for it to be executed.
In the case of window.open, both windows must share a single context to keep it thread-safe because the opened window can access to it's parent using window.opener.
I don't know how browsers implements it, but we can guess two possibilities:
Idle time is shared between the two windows. It means if the popup does many blocking statements, it can freeze the main window's events.
Only one of the two windows can be active, which depends on which one has the focus. In that case, all events may be paused in the main window when you're using the popup.
If you want a more precise answer, I need more details about your code.
document.addEventListener("DOMContentLoaded", function () {
//whatever the code
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
}, false);
Try to wrap the code in SetTimeout
setTimeout(function () {
window.open( .. )
}, 0);
Your document should be loaded first, then popup should be open, So write your javascript code in the scope of $(document).ready().
enter code here
$(document).ready(function(){
$("#clickme").click(function(e){
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
});
});
UPDATE: there is something going on with the page I am trying to have the onbeforeunload work on. I set it up in the layout and it pops up for every page besides that one... So there has to be some broken javascript, or a javascript file that redefines onbeforeunload. Since it can only be defined once
I am working on a Rails project and I am setting up a pop up to alert the user that their data will be lost if they leave the page without saving. So I am using window.onbeforeunload
I set it up on one page by adding this script code to the top of the view file
var saving = false;
window.onbeforeunload = function(){
if(!saving)
return 'Are you sure you don\'t want to save before you leave?';
};
where saving is set to true if the user hits the save button, which redirects them to a separate page.
The problem is coming up when I try to set up the EXACT same thing on a separate view file, that also needs the same functionality.
Except when I drop the code above into the file no pop up is given, at all... at any point. So then I looked around at other available options to set up the onbeforeunload function.
So I currently have it set up as:
var saving = false;
window.onbeforeunload = displayConfirm();
function displayConfirm(){
if(!saving){
if(confirm('If you leave without saving, your changes will be lost. Press cancel to go back to save')){
confirmExit();
}
}
}
on the second page. My issue is the pop up here doesn't work the same as the first implementation. Even weirder, the pop up shows up on window load... NOT before window unload.
I have been looking around and messing around with this for a few hours now. I am starting to get really irritated since this should have been an easy addition. Seeing as how it is already set up on a separate page, and working correctly. Any insight onto what maybe going wrong, or if I am making a stupid mistake, would be greatly appreciated.
Thanks,
-Alan
1) window.onbeforeunload = displayConfirm(); -- you're firing the function, instead of assigning it
2) onbeforeunload is great, but it's unsupported in a lot of ways. Some browsers don't even have it, period (all but the most recent Opera, for example), so if you're doing this for a wide audience, or you need it to work 100% cross-browser, onbeforeunload is sadly not enough on its own.
Try with
window.onbeforeunload = displayConfirm;
You are actually calling the function right away and assigning the return value of displayConfirm() to window.onbeforeunload.
Update
But you are limited to exactly one return statement in your onbeforeunload-function, see here. So calling "confirm" or some other custom function does not work.
Recently i was working on a project using this event, so i did do some search on the net.
There are few thing need to be taken into consideration when using the onbeforeunload event.
It is not supported by all browser. Opera, especially older version.
Some support it partially, such as not firing when refresh button is pressed.
Using this event will cause the page will not be cached.
Here is an article that is more thorough about the onbeforeonload event by Patrick Hunlock.
I am writing an android (2.2) app which launches the default native web browser via a new Intent to a page I've created. On that page, it pauses for 2 seconds before then submitting a form, which redirects the user to another page.
I am using javascript's setTimeout() function.
It works most of the time, but then sometimes it just stops working, and won't work again until I restart the phone!
There are NO javascript errors which appear in LogCat.
Even stranger, to counteract this I put a link on the page that says "If the page has not redirected in 5 seconds click here". It submits the form when clicked, via onClick() and .submit(). Well, again, it usually works, but, when the setTimeout() function stops working, so does the link! But, I have confirmed that alert() still works, so some javascript functions apparently still work.
Any ideas why setTimeout() and .submit() would just randomly stop working, until the phone is reset?
EDIT: I've also confirmed that window.location doesn't work anymore either, but, if you just have a regular link, it does actually let you click on it, and it leaves the page.
EDIT: It appears that you can get this problem to happen more quickly if you hit STOP and REFRESH a few times while waiting for the setTimeout to fire off. Basically if I hit stop, then refresh, then stop, then back, etc, a couple times, I can get this problem to happen. After it starts, no amount of refreshing or killing/restarting the browser will make these javascript functions start working again.
Thanks!
Richard
I came across this post that may be of help: http://www.barneyb.com/barneyblog/2011/02/20/settimeout-bug-in-android-2-2/
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.)