Why is my JavaScript function sometimes "not defined"? - javascript

I call my JavaScript function. Why do I sometimes get the error 'myFunction is not defined' when it is defined?
For example. I'll occasionally get 'copyArray is not defined' even in this example:
function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
return la;
}
Function.prototype.bind = function( po ) {
var __method = this;
var __args = [];
// Sometimes errors -- in practice I inline the function as a workaround.
__args = copyArray( arguments );
return function() {
/* bind logic omitted for brevity */
}
}
As you can see, copyArray is defined right there, so this can't be about the order in which script files load.
I've been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem.
It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what.
#Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function.
#James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error.
#David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section.
#Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn't work.
#sk: This technique has been tested across browsers and is basically copied from the Prototype library.

I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.
What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way:
<SCRIPT src="mycode.js"/>
(That is, without the closing tag.)
I had to redeclare this block in the following way.
<SCRIPT src="mycode.js"></SCRIPT>
And then what followed worked fine... weird huh?

It shouldn't be possible for this to happen if you're just including the scripts on the page.
The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency library. There are all sorts of problems with timing if that's the case.

My guess is, somehow the document is not fully loaded by the time the method is called. Have your code executing after the document is ready event.

Verify your code with JSLint. It will usually find a ton of small errors, so the warning "JSLint may hurt your feelings" is pretty spot on. =)

A syntax error in the function -- or in the code above it -- may cause it to be undefined.

This doesn't solve your original problem, but you could always replace the call to copyArray() with:
__args = Array.prototype.slice.call(arguments);
More information available from Google.
I've tested the above in the following browsers: IE6, 7 & 8B2, Firefox 2.0.0.17 & 3.0.3, Opera 9.52, Safari for Windows 3.1.2 and Google Chrome (whatever the latest version was at the time of this post) and it works across all browsers.

If you're changing the prototype of the built-in 'function' object it's possible you're running into a browser bug or race condition by modifying a fundamental built-in object.
Test it in multiple browsers to find out.

This has probably been corrected, but... apparently firefox has a caching problem which is the cause of javascript functions not being recognized.. I really don't know the specifics, but if you clear your cache that will fix the problem (until your cache is full again... not a good solution).. I've been looking around to see if firefox has a real solution to this, but so far nothing... oh not all versions, I think it may be only in some 3.6.x versions, not sure...

Solved by removing a "async" load:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script>
changed for:
<script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script>

Use an anonymous function to protect your local symbol table. Something like:
(function() {
function copyArray(pa) {
// Details
}
Function.prototype.bind = function ( po ) {
__args = copyArray( arguments );
}
})();
This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.

This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame.

I'm afraid, when you add a new method to a Function class (by prtotyping), you are actually adding it to all declared functions, AS WELL AS to your copyArray(). In result your copyArray() function gets recursivelly self-referenced. I.e. there should exist copyArray().bind() method, which is calling itself.
In this case some browsers might prevent you from creating such reference loops and fire "function not defined" error.
Inline code would be better solution in such case.

I think your javascript code should be placed between tag,there is need of document load

Related

Javascript function is undefined only in IE11

I'm trying to use a template but just realized that the javascript doesn't work at all in IE.
It fails in several places but here is the first one:
I have this tag, immediately before my </html>:
<script>
document.addEventListener("DOMContentLoaded", function (event) {
navbarToggleSidebar();
navActivePage();
});
</script>
The exception says, "0x800a1391 - JavaScript runtime error: 'navbarToggleSidebar' is undefined occurred"
The javascript file that came with this template was minimized as uses some cracy javascript markup that I've never seen and do not understand. But when I do a find in the whole solution for navbarToggleSidebar I only find this:
JkW7: function (t, e, n) {
"use strict";
Object.defineProperty(e, "__esModule", {
value: !0
});
var i = (n("PExH"), n("juYr"), n("6wzU"), n("e9iq"), n("aWFY"));
! function (t) {
t.keys().map(t)
}(n("pax0")), Object.assign(window, {
masonryBuild: i.a,
navbarToggleSidebar: i.c,
navActivePage: i.b
})
},
I can post the whole file somewhere (just tell me where, it's too long to paste here) if that's helpful because this is clearly just a piece of a huge js thing that I don't understand at all. I like to think I'm fairly decent with js and jquery and this looks greek to me. And it all works beautifully in Chrome and FF.
Can anyone help me figure out what's going on?
Thanks!!
Well n is a callback function t is an array or a list of some kind most likely; so in order for you to figure out what is actually happening in the function you have to figure out where the function was actually invoked. It is much easier to find out what library was used and see if it is hosted anywhere in a non-minified version.
Sometimes this is done intentionally in order to protect developers from other people having an easy time engineering their solutions to programming problems.
Basically in order for anyone to figure out what the function actually does, you would have to print the entire page library, then trace through it, then when you are done after about a month you will have your answer.
Arrays, callback functions, as well as a probably system variable and object literals are used in that function.

In newer versions of Firefox, is it still possible to override a web page's JS function?

I am writing an extension to override a web page's JS function, and started from this question, but the answer does not appear to work in Firefox 42 on Linux.
Next, I tried to use exportFunction as described in the documentation, but that also silently failed.
Inside package.json, I have added the following sesction.
"permissions": {
"unsafe-content-script": true
}
Here is my index.js file.
var self = require('sdk/self');
require("sdk/tabs").on("ready", fixGoogle);
function fixGoogle(tab) {
if (tab.url.indexOf("google.com") > -1) {
tab.attach({
contentScriptFile: self.data.url("google-script.js")
});
}
}
Here is my current data/google-script.js.
unsafeWindow.rwt=function(){};
Note that manually typing in rwt=function(){}; to the browser's console achieves the desired effect, as does using a bookmarklet (which requires clicking) but I am writing the plugin to get this automatically every time I use Google.
Is it possible to override the rwt page function using a Firefox extension? If so, what is the correct API to use?
read the documentation you've linked to, specifically the chapter titled Expose functions to page scripts - which links to exportFunction
function blah() {}
exportFunction(blah, unsafeWindow, {defineAs: 'rwt'});
It turns out that the issue is that the redefinition of the function rwt is racing against the original definition and winning. The original runs after and overrides the function I defined, thereby making it look like my redefinition had silently failed.
Once I realized that this was the problem, the easiest hack around it was to add a timeout to the redefinition inside data/google-script.js.
setTimeout(function() {
unsafeWindow.rwt=function(){};
}, 1000);
Thus, the orignal answer is still correct but simply failed to address the race condition.
Even though content scripts share the DOM, they are otherwise isolated from page scripts. As you correctly surmised, one can use unsafeWindow in Firefox to bypass this isolation.
Personally, I don't like the name of unsafeWindow for some reason ;)
Therefore I propose another way to do this: make use of the thing that's shared between these scopes, i. e. DOM.
You can create a page script from a content script:
var script = 'rwt=function()();';
document.addEventListener('DOMContentLoaded', function() {
var scriptEl = document.createElement('script');
scriptEl.textContent = script;
document.head.appendChild(scriptEl);
});
The benefit of this approach is that you can use it in environments without unsafeWindow, e. g. chrome extensions.

Function Undefined: Must a javascript function be defined within the same file?

I've got a file notifications.js containing one event bound to an element, and a function updateNotification(). This function uses jQuery to update certain elements on the page when a JSON object is passed as a parameter.
The problem:
I'm attempting to call this function within the page (via <script> tags), however rather than calling it, it breaks the page. I did some digging around within the Chrome Developer Console (not sure of the name), and an error is flagged:
/pleaseshare/views/install/:50 Uncaught ReferenceError:updateNotification is not defined
However, when I pan within the console, I can clearly see the file notifications.js listed under scripts, and the function is defined there. If I define the function within the current scope (e.g. the line above the call), it works fine.
What I've tried
The function contains some javascript that requires jQuery, so I've attempted both with and without encasing it in $(document).ready( function() {});, with neither seeming to have any affect.
I'm pretty stumped.
For good measure, here's a link to show the structure of my javascript and html: http://snippi.com/s/znk6xe9
Any help in figuring out why this is happening, or explanations of why javascript functions cannot be called cross-file (although I'd hope this isn't the case), would be greatly appreciated ;)!!
A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.
A function cannot be called unless it is in the same or greater scope then the one trying to call it.
You code looks like the structure should work, but is clearly a reduced test case that has been reduced to the point where it won't.
Got it working. The issue was definitely multi-faceted, but I figured it out.
First off the use of RequireJS had an impact on updateNotification(), in that it couldn't be called cross-file, and was therefore considered undefined. I assume this because of how RequireJS loads files, and I'll look into the documentation later (and post an edit if I find anything relevant).
Secondly, updateNotification() would again be considered undefined when encased within jQuery's DOM ready loader $(document).ready(function(){}). However updateNotification() contains executions which require jQuery, so I had to encase the contents of the function in $(document).ready(function(){}).
This is an issue very unique to RequireJS/jQuery, hence why in most use cases this wouldn't occur.
Side note: The tags are edited to reflect this.
you need to import your script into your page:
<script type="text/javascript" language="javascript" src="path/to/notifications.js"></script>
This needs to be added above the <script> tag that calls updateNotification()
Functions do not need to be declared in the same file. In fact, avoiding having every declaration dumped into the global namespace is usually a concern in JavaScript.
In the sample code in the link you provided, updateNotification is declared as a global, so there should not be a scoping problem.
However, in the same sample, you don't show notifications.js being included. You need to import it using a <script></script> element and that element must come before the script element that includes the call to updateNotification. You also must include jQuery before notifications.js, since it uses jQuery. So you need something like:
<body>
// One or two elements
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="notifications.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var json = {status : 'ok', message: 'Hello'};
updateNotification(json);
});
</script>
// All other elements
</body>

Why would Dojo 1.6 fail to properly load javascript file in IE8 using dojo.require?

The following code worked with Dojo 1.5 in Firefox and Internet Explorer 8.
With Dojo 1.6, it still works in Firefox, but does not work in IE8.
I get an Object doesn't support this property or method error when wrappingFunctionInPlainJsFile() is called.
HTML page:
<div dojoType="widget.MyCustomWidget"></div>
In widget/MyCustomWidget.js
dojo.provide("widget.MyCustomWidget");
dojo.require("js.plainJsFile");
dojo.declare("widget.MyCustomWidget", [dijit._Widget, dijit._Templated], {
...
// this gets called when the widget is clicked on in the UI
run: function() {
wrappingFunctionInPlainJsFile();
},
...
});
In js/plainJsFile.js
dojo.provide("js.plainJsFile");
function someFunction() {
}
function wrappingFunctionInPlainJsFile(){
new someFunction();
}
Any ideas on what I am doing wrong would be greatly appreciated.
Note: If I import the plainJsFile.js directly on the HTML page instead of using dojo.require then I have no problems.
I believe that the purpose of the dojo.require system to break your code up into modules where those modules aren't just arbitrary chunks of js, but dojo.declare'd objects. When you write dojo.provide("js.plainJsFile"), by convention I'd expect there to be an global object called "js" which had a property "plainJsFile". See the code example on this page.
I actually use dojo.require the way that you do, ignoring the convention I'm describing, and it works just fine -- in firefox. IE won't swallow it though. IE will behave if all the required js files are compressed into a single file (which you mentioned solves your problem).
So, basically, I think that IE is less flexible about scope while dojo.require is doing its thing, and you putting function declarations in a "module" like that is breaking things. Try going with the convention and see if that helps.
I tried the dojo mailing list and got a fix courtesy of Karl Tiedt.
See here: http://dojo-toolkit.33424.n3.nabble.com/Why-would-Dojo-1-6-fail-to-properly-load-javascript-file-in-IE8-using-dojo-require-td3204800.html#a3204894
Copy/paste of solution.
"Its an IE quirk....
dojo.provide("js.plainJsFile");
(function() {
function someFunction()
wrappingFunctionInPlainJsFile = function() {
new someFunction();
}
})();
should work... I always use my name spaces though and do it this way
dojo.provide("js.plainJsFile");
(function(pjsf) {
pjsf.someFunction = function()
pjsf.wrappingFunctionInPlainJsFile = function(){
new someFunction();
}
})(js.plainJsFile);
"
Note: I tried the above solution and it worked for me in IE8 and Firefox.

"Error calling method on NPObject!" in Uploadify

I'm using Uploadify to upload file in my CMS. Everything works fine until recently. I got an error
Error calling method on NPObject
on this line
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
on this part
uploadifyUpload:function(ID,checkComplete) {
jQuery(this).each(function() {
if (!checkComplete) checkComplete = false;
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);
});
},
I don't know why and after a day debugging and testing I found that if I remove replace(/\&/g, '\\&') from
String.prototype.escAll = function(){
var s = this;
return s.replace(/\./g, '\\.').replace(/\?/g, '\\?').replace(/\&/g, '\\&');
};
It then works again. I really don't know why.
Any helps would be appreciated!
I think the reason is in additional Javascript libraries you use.
Some libraries (for example Prototype.js or jQuery.js) change behaviour of your code. For example, you can't overload prototype in some cases. The result may be undefined in clear (obvious) places (like you use an array variable with wrong index). You should view the source code of additional libraries, probably they do with prototype something that breaks your code in the function you mentioned.
In my practice I had the situation when overloading of prototype worked incorrectly (it was String prototype like in your case).
So just don't use prototype.

Categories

Resources