window.onload not working chrome dev console - javascript

window.onload doesn't seem to run the specified function in the chrome console and I can't seem to find anyone with the same problem.
Code:
function preStart() {
console.log("Hello");
}
window.location = 'https://www.google.com/';
window.onload = preStart;
When ran the window.location successfully runs but "preStart" does not. Any help with this would me much appreciated.
Edit - Ben Hanna says .onload will not activate because the page is changed which is fine but is there a solution to this? (where the function runs after the page changes)

This code will never hit the onload event if you're changing the location to navigate away to another page.
Update: You could do something like this.
function preStart() {
// You can run a function like this before navigating
console.log("Hello");
window.location = 'https://www.google.com/';
// You can't run a function once you've navigated to Google
// because you can't execute arbitrary scripts on pages/domains
// that you don't own.
}
// preStart will be executed when the `onload` event fires
window.onload = preStart;

Related

window.onload not working after page load in chrome developer console

window.onload doesn't seem to run the specified function in the chrome console and I can't seem to find anyone with the solution.
Code:
function preStart() {
console.log("Hello");
}
window.location = 'https://www.google.com/';
window.onload = preStart; //Please note, adding brackets here doesn't fix the problem
When ran the window.location successfully runs but "preStart" does not.
I realize that window.onload doesn't work after window.location but is there a solution to this? (Where the function runs after the page loads)
Since I am relatively new to JavaScript please explain any answers/solutions.
Any help with this would me much appreciated.
Note - I have tried setTimeout with the following and it still doesn't work:
function preStart() {
console.log("Hello");
}
window.location = 'https://www.google.com/';
setTimeout(preStart,2000);
Your onLoad method is fine, but you are canceling it by changing the window.location before it is run.
Try adding the window.location at the end of the preStart() method to ensure your script is run before the change of window location cancels it:
function preStart() {
console.log("Hello");
window.location = 'https://www.google.com/';
}
window.onload = preStart;
Also, the console is cleared on a new page load, so even if you do have "hello" printed, you might not get the chance to see it. Try using alert("hello") to check if code is being executed instead:
function preStart() {
alert("hello");
window.location = 'https://www.google.com/';
}
window.onload = preStart;

Chrome window onunload event

I'm trying to execute the following code
window.onunload = function () {
var sTag = document.createElement('script');
sTag.src = 'mysrc';
document.getElementsByTagName('head')[0].appendChild(sTag);
return false; };
}
Itseems to work fine in FF but in chrome I'm getting the download status as cancelled as soon as the unload event is fired. I saw some posts in SO with ajax solutions but I'm executing this script inside a cross domain iframe. Im just trying to log the time for which my api was live in a page per visitor. So, I'm sending some time log information on unload of the page. Is there any work around for the above?
For the purpose of what you described, you can have that script loaded in your page or parent window (you are saying it is an iframe right?) and run a function on window.unload:
window.onunload = function(){
window.top.logtime(); // if it is in the parent, or
window.logtime() //if it is in the same window
};
and don't return false, unload event cannot be cancelled. (in best cases, the user gets an alert dialog that will override the return false statement.)
I think what makes this different is how fast it carries out a new function, before the body gets unloaded. Manipulating the DOM is definitely much slower than making a call.

IE9 not running javascript onload

For some reason, IE9 is not running my JavaScript code onload when the browser is launched for the first time that session. It seems to only run onload after the user refreshes the page. It will also run the JavaScript when the debug console is open.
How do I make it so the JavaScript runs onload after the browser is open? Is this just a bug of IE9?
I'll restate this so you understand: The code DOESN'T run if you go to the site after launching a new browser session. The code DOES run if you open the site in a new tab, or reload the page, or open the debug console
Here is the function I use to run my script onload (which works fine in NORMAL browsers):
(function (i) {
var u = navigator.userAgent;
var e = /*#cc_on!#*/
false;
var st = setTimeout;
if (/webkit/i.test(u)) {
st(function () {
var dr = document.readyState;
if (dr == "loaded" || dr == "complete") {
i()
} else {
st(arguments.callee, 10);
}
}, 10);
} else if ((/mozilla/i.test(u) && !/(compati)/.test(u)) || (/opera/i.test(u))) {
document.addEventListener("DOMContentLoaded", i, false);
} else if (e) {
(function () {
var t = document.createElement('doc:rdy');
try {
t.doScroll('left');
i();
t = null;
} catch (e) {
st(arguments.callee, 0);
}
})();
} else {
window.onload = i;
}
})(init); //init is the function to call onload
I had the exact same issue that you had. I had a set of images that I wanted to ensure were preloaded before I began starting a slideshow. I was making use of
$(window).load(function(){
//All my code
});
And this is exactly what I was facing.
When I copied and pasted the URL in IE, the onload event did not seem to fire.
If I open the console using F12 and then past the URL in the browser and pressed enter, the everything seemed to be working.
Now that I opened the console at least once,
If I closeed the console and then reloaded the page, the onload was firing.
If I typed the URL and then pressed enter, the onload was firing.
It took me a couple of days to actually figure out what I was doing wrong.
The issue was with the console.log statements. At a lot of places in my code, I had done a lot of console logging. Even one of the plugins that I was using - jplayer has a an uncommented console message somewhere in the code.
The issue was that, unless you open the console at least once in IE, the console object is not available. Which means that the code will fail at the first console.log that it encounters.
Now, I was in no mood to comment out all my console.log statements just for the sake of testing it in IE. So, this is what I did instead. Right at the top of my document.ready jquery function, I wrote this small snippet of code.
if(!window.console){
console={};
console.log = function(){};
}
What it basically does is creates a dummy console.log function placeholder so that the code can run in IE but it will work only as long as console.log is the only console function that you are making use of in your code or in your plugins.
Just my 2 cents. Been pulling my hair over this issue for longer than I care to admit. I hope this is useful to at least someone.
You need to figure out if the code doesn't run at all, I.e. never enters your function, or if it fails on some specific line inside your function. Does IE9 show any warnings or js errors?
The easiest thing to do is stick a bunch of alert() statements in the code to see where it stops and narrow down to that line.
If it never enters your function then you need to look higher, where the call is being made.
Just a small note; When you use any debugging keywords (like console.log) or anything related, IE9 will escape this JS function if and only if the debugger is not on (with F12)
Actually I don't know what else cause a problem, but for me, my problem was the word "console.log" while debugger not on in IE9 ... I know this is already an answered question, but I felt it needs to be be known.
Okay, I figured it out. It has to do with some weird way IE handles IF statements.
In my init function I had two IF statements, one which checked if a variable existed and then logged the value of that variable. The other which checked to see if the value of the same variable was equal to an arbitrary string.
After removing the first IF statement, everything seems to work properly. I also decided to use a different onload function which can be seen below:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, true);
} else if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag=document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete") {
init();
//ie('open');
}
}
}

Why is this setTimeout not working & related question inside

I have this script on a page of mine and the setTimeout function never fires. It's just an alert right now but i'm just testing it out. I'm doing a meta refresh on the page just after it if that's any clue, but i've also given that a 10 sec delay so the page isn't refreshed before it's supposed to trigger.
Also, the related question: If I run a javascript with a delay of, say, 10 seconds (with setTimeout) and in that javascript I try to modify a design element that's not on the page when the setTimeout is declared but will be by the time the script is fired. Will it work?
<script language=javascript>
var xmlhttp_get_memento;
function loop_alerte(){
setTimeout( function() {
alert("timeout");
}, 5000);
xmlhttp_get_memento = new XMLHttpRequest();
if (xmlhttp_get_memento==null)
{
alert ("Browser does not support HTTP Request (1)");
return;
}
var url="crm/ajax/get_mementos.php";
url=url+"?sid="+Math.random();
xmlhttp_get_memento.onreadystatechange=function() {
if (xmlhttp_get_memento.readyState == 4) {
alert(xmlhttp_get_memento.responseText);
schimbare_tip_cursor("default");
}
else{
schimbare_tip_cursor("progress");
}
};
xmlhttp_get_memento.open("GET",url,true);
xmlhttp_get_memento.send(null);
}
loop_alerte();
</script>';
Your setTimeout looks good, so there's probably something else that's wrong. Have you tried using a javascript debugger to see if you get any errors?
As for your second question, yes, that shouldn't be any problem, as the anonymous function inside the setTimout won't be evaluated until it runs. Live sample here: http://jsbin.com/afonup/2/edit Both with and without jQuery.
There is nothing wrong with your setTimeout, you will need to debug further
As for your second question -- the function will run, but whatever it is you were trying to do will not work.
Cleaning up your code would be a nice start. I can imagine a browser doesn't understand the tag <script language=javascript>. I suggest to use <script type="text/javascript"> and if you're lucky, your javascript might work!

gBrowser.addEventListener: "load" event fired three times

I have installed the "hello world" dev example for Firefox extensions as described here:
http://blog.mozilla.com/addons/2009/01/28/how-to-develop-a-firefox-extension/
I have modified the anonymous function that gets passed to gBrowser.addEventListener:
gBrowser.addEventListener("load", function (event) {
var t = event.target;
alert("Content title: " + t.contentTitle);
}, false);
This function is getting called three times for every page load. When I click a link, it fires twice for the current (already loaded page) and once for the new page.
I have uninstalled all other addons (including Firebug) and still it fires 3 times. Does anyone know why this might be?
Thanks Richard
I would recommend you to do something like this:
window.addEventListener("load", function load() {
window.removeEventListener("load",load,false); //no longer needed
window.gBrowser.addEventListener('DOMContentLoaded', function load(event) {
your_addon.init_function(event);
}, false);
In my addon it works. :-)
Hope this helps.
MichaƂ

Categories