Javascript: 'window' is not defined - javascript

I'm trying to learn JavaScript, but the following code has been giving me a lot of trouble:
window.onload = function () {
for ( var i = 0; i < seats.length; i++) {
for ( var j = 0; j < seats.length; j++) {
document.getElementById(getSeatId(i, j)).onclick = function(evt) {
getSeatStatus(getSeatId(i, j));
};
}
}
document.getElementById("search").onclick = findSeat;
document.getElementById("male_search").onclick = findMaleSeats;
initSeats();
};
It is from an external JS file and it is the only file linked to the page. findSeat, findMaleSeats, getSeatId, and initSeats are all defined a little bit later in the file. When I double click this file, I get the following error:
Windows Script Host
Error: 'window' is not defined
Code: 800A1391
I already tried moving the code to other places in the file, assigning a different function (even an empty function) to window.onload and many other things. It just seems that my computer doesn't know what window is. And if I try to open the HTML in a browser the nothing loads (as one would expect).
Does someone know what is wrong with this?

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

Trying to access an undefined variable will throw you a ReferenceError.
A solution to this is to use typeof:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

Related

Best Practice : Call a function from chrome dev console [duplicate]

In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName(); and hit return.
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
})
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
})
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox):
http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.

Undefined jscript in javascript

I have created an ASP.Net application. I am using a javascript which is written in a separate file. I am using Var myvariableName ={} in javascript file.
I have included this file in MasterPage and accessing myvariableName in my aspx page.
This is working fine in Google Chrome, however, in IE 8 an unhandled exception is thrown as
myvariableName is undefined.
the error shows as;
0x800a1391 - Microsoft JScript runtime error: 'Common' is undefined
where Common is my javascript variable.
Please assist me in resolving this issue.
You're probably accessing the variable before your external script is executed.
Be sure to access your variable as soon as the document is fully loaded (i.e. $(document).ready(function(){...}); if you use jQuery) or try to find out the real execution order with some alert (that shouldn't be browser-depentent, by the way!).
If your code is already in a document.load or $(document).ready(function) you can always
handle the variable before acessing it via
if (typeof myvariableName !== "undefined") {
// do stuff
}
Some times in IE shit happens and window.load gets screwed specially when async calls are in place.
You are probably getting this error due to a missing semicolon. Change the code to this:
var myvariableName = {};
In your asp page, where you access your custom variable, wrap your code with:
var myvariableName = {};
window.onload = function(){
// your code here where you're accessing the variable
};

Safari generates "Can't find variable" error although it is already defined in another Javascript page

The JavaScript script works with Chrome and Firefox but not in Safari. The code is:
$(document).ready(function(){
$(window).load(function() {
myVariable.start();
});
This generates:
ReferenceError: can't find variable: myVariable
The variable is defined in another JavaScript page that is included in this page, but for some reason Safari doesn't see the definition in the other page. Is Safari executing this script without loading the page that the variable is defined in?
How can I fix this?
Thanks for any help
Try to avoid setting global variables.
Maybe try assigning your variable to the window object, on top of the page:
window.myVariable = { start: function() {} };
Then when you need it:
$(window).load(function() {
window.myVariable.start();
});

Safari Extension safari.application error

I'm making an extension for safari I created a context item with command = showNote
In debugger I get the follwing error TypeError: Result of expression 'safari.application' [undefined] is not an object on line 8(the last line)
are there any things you need to include or call before this works?
main.js
function showNote(event){
if(event.command == "showNote"){
addElement = document.createElement('<div id="safExtNote"><textarea id="safExtNoteText"></textarea><button id="safExtSave">Save</safExtNote></div>');
document.body.appendChild(addElement)
alert("im online");
}
}
safari.application.addEventListener("command", showNote, false);
Just ran into this problem myself trying to create a toolbar command. Turns out I was putting the JS in the wrong place. I added it to the "Injected Extension Content" as a start script. Needed to create an HTML page that included the JS and set that as the Global Page File.
Switch that around and you should be set, assuming it's the same problem I just ran into.

Javascript: Error 'Object Required'. I can't decipher it. Can you?

I am using a javascript called 'Facelift 1.2' in one of my websites and while the script works in Safari 3, 4b and Opera, OmniWeb and Firefox it does not in any IE version.
But even in the working browser i get the following error I cannot decipher.
Maybe in due time—with more experience in things Javascript—I will be able to but for now I thought I would ask some of you, here at SO.
The following is the error popup i get in IETester testing the page for Interet Explorer 6,7 and 8:
The following is from the Firebug console in Firefox 3.0.6:
The website is: http://www.457cc.co.nz/index.php In case it helps you see the problem mentioned in action.
I have also looked up what line 620 corresponds to which is:
"line 76" is:
this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
which is part of this block of code (taken from the flir.js):
// either (options Object, fstyle FLIRStyle Object) or (fstyle FLIRStyle Object)
,init: function(options, fstyle) { // or options for flir style
if(this.isFStyle(options)) { // (fstyle FLIRStyle Object)
this.defaultStyle = options;
}else { // [options Object, fstyle FLIRStyle Object]
if(typeof options != 'undefined')
this.loadOptions(options);
if(typeof fstyle == 'undefined') {
this.defaultStyle = new FLIRStyle();
}else {
if(this.isFStyle(fstyle))
this.defaultStyle = fstyle;
else
this.defaultStyle = new FLIRStyle(fstyle);
}
}
this.calcDPI();
if(this.options.findEmbededFonts)
this.discoverEmbededFonts();
this.isIE = (navigator.userAgent.toLowerCase().indexOf('msie')>-1 && navigator.userAgent.toLowerCase().indexOf('opera')<0);
this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
if(this.isIE) {
this.flirIERepObj = [];
this.flirIEHovEls = [];
this.flirIEHovStyles = [];
}
}
The whole script is also available on my server: http://www.457cc.co.nz/facelift-1.2/flir.js
I just don't know where to start looking for the error, especially since it only affects IE but works in the rest. Maybe you guys have an idea. I would love to hear them.
Thanks for reading.
Jannis
PS: This is what Opera's error console reports:
JavaScript - http://www.457cc.co.nz/index.php
Inline script thread
Error:
name: TypeError
message: Statement on line 620: Cannot convert undefined or null to Object
Backtrace:
Line 620 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
document.body.appendChild(test);
Line 70 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
this.calcDPI();
Line 2 of inline#1 script in http://www.457cc.co.nz/index.php
FLIR.init();
stacktrace: n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
I agree with tvanfosson - the reason you're getting that error is quite likely because you're calling init() before the page is done loading, so document.body is not yet defined.
In the page you linked, you should move the following code to the bottom of the page (just before the closing html tag:
<script type="text/javascript">
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
</script>
Even better, you should attach the initialization to the document's ready event. If you do it this way, there is no need to even move your javascript to the bottom of the file. Using jquery:
$(document).ready( function(){
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
});
More on jquery's document.ready event »
Edit Answer left for context. See #Triptych's (accepted) answer for the correct resolution.
My suggestion is to move the inclusion of the javascript to the end of your mark up. I think what is happening is that the code is executing before the DOM is completely loaded and thus the document.body is null when you try to reference it in determining the maxHeight style property. Moving the inclusion of the javascript to the end of your markup should be enough to guarantee that the body of the document is loaded at least and avoid this particular error.
... rest of html....
<script type='text/javascript'
src='http://www.457cc.co.nz/facelift/flir.js'>
</script>
</body>
</html>
Install .net Framework v2 and solve the problem.

Categories

Resources