Good day all.
I would like to count the js functions present on a given page, and then send this number via ajax (the ajax part is the simple part) do you think is it possible to achieve that in javascript? what should be the best way to do it?
thanks in advance.
explanation:
I'm trying to figure out how to counter measure some fraud attempts on some subscription pages, I suspect that some javascript is injected on the page before the user click, so having the number of functions present at the load event, and then the number of those present on the submit event, should lead me in the right direction.
Well, if someone is injecting code to your site, they could just as easily use that code to turn off your code counting functions. You can never trust anything that happens on the client side and must validate everything on the server.
As for the technical side, you'd use a tool like acorn to traverse the syntax tree and find all FunctionDeclaration and FunctionExpressions (and arrows, concise method definitions and methods). That would not find all functions, but it would find all statically created ones.
Once the code started executing it's impossible since it's easily reducable to the halting problem. You don't know if a code will create a function at some point in the future.
Related
I don't understand how does ECMAScript works. Check on MSDN and other forum it didnt tell us which version or values equal to javascrpt.
if (!Request.Browser.JavaScript)
//Do Something.
However, I was given a warning of obsolute and recommend me to use ECMAScript instead.
System.Web.HttpBrowserCapabilities myBrowserCaps = Request.Browser;
if (((System.Web.Configuration.HttpCapabilitiesBase)myBrowserCaps).EcmaScriptVersion.Major < 1)
//Does not have Javascript. Do something.
However, I tried both on/off my javascript. Somehow the function was not fired. I suspect certain values belong to javascript. However, I cant find anything related to value == javascript.
I understand I could a Then perform a redirect using meta tag. But I would like all these code to perform at the server.
First of all, see Should I bother to develop for JavaScript disabled? / How important is graceful degradation of JavaScript? .
Then, client-side Javascript only exists in the client and if it's off, no client-side logic will fire to check anything explicitly. So you cannot know it until the client sends at least one reply from your page (be it a GET/POST query or an XMLHTTPRequest) - i.e. only after the second request from that very user, generated by the very page you sent them, which may never occur if they just lurk around, even if you make every link on your page a form reply - they may use URLs from an external source. A CodeProject article linked from Check if javascript is disabled? is one example of such approach.
For this reason (and to avoid effort duplication to make both script and noscript versions - the practice that saw some use in the past), the best practice appears to have become making pages and frameworks JavaScript-agnostic and just warning the user with <noscript> that the page may not be fully functional if it's relevant.
E.g. Sharepoint does just that - with JS disabled, a warning appears on top while on the page, there are e.g. no scrollbars and editing is disabled completely. Which leads to conclusion that ASP.NET controls (which SP makes heavy use of) weren't designed to be functional beyond basic display with JS disabled in the first place.
I am making a website and I want to use the following design:
Each time a user clicks a link an ajax request is sent.
The reply contains 2 fields:
the HTML that replaces the content area
A JavaScript to be evaluated (JavaScript behaviors attached to objects withing the new HTML content)
Does this use of JavaScript eval() have any downsides?
Edit
The JavaScript that is to be evaluated is varied - it's not something that can be sensibly expressed with a single function taking different arguments.
Cross-site scripting was mentioned, but I don't see how this use is different from a user visiting a new JavaScript-containing page.
This mainly depends upon how the javascript to be evaluated is generated. Any use of eval is potentially subject to cross site scripting, but only if the js is generated by something that a user can control. If the server is returning a static js, that's no more inherently bad than the use of js anywhere else.
Can't think of any, although my imagination may be a bit lacking. ) Besides, isn't JSONP something of the same method?
I recently ran into a situation where it made sense (at first at least) to have my server-side code not only "print" html, but also some of the javascript on the page (basically making the dynamic browser code dynamic itself). I'm just wondering if there is sometimes a valid need for this or if this can usually be avoided...basically from a theoretical perspective.
Update:
Just to give an idea of what I'm doing. I have a js function which needs to have several (the number is determined by a server-side variable) statements which are generating DOM elements using jQuery. These elements are then being added to the page. So. I am using a server-side loop to loop over the number of elements in my object and inside of this loop (which also happens to be inside of a js function) I am aggregating all of these statements.
Oh and these dom elements are being retreived from an xhr (so the number of xhr requests is itself a server-side dependency) and then processed using jQuery..which helps explain why im not just printing the static html to begin with. Sounds kind of ridiculous I'm sure, but its a complicated UI..still I'm open to criticism.
I can smell some code smell here... if you're having to generate code, it probably means one of:
you are generating code that does different things in different situations
you are generating same kind of functionality, only on different things.
In case 1, your code is trying to do too much. Break your responsibilities into smaller pieces.
In case 2, your code is not generic enough.
Yes there is sometimes a need and it is done often.
Here is a simple usage in an Asp.net like syntax
function SayHi( ){
alert( "Hello <%= UserName %>");
}
Just a suggestion. If your server-side is generating HTML/Javascript, then you're letting view-side logic creep into your server-side. This violates separation of concern if you're following an MVC-style architecture. Why not use a taglib (or something of that nature) or send JSON from the server-side?
One usefull feature is to obfuscate your javascript on the fly.. When combined with a caching mechanism it might actually be useful. But in my opinion javascript generation should be avoided and all serverside variables should be handed to the script from the templates (on class or function init) or retrieved using XMLHTTP requests.
If your application generates javascript code only for data (eq. you want to use data from sql in js), the better practice is to use JSON.
Yes, sometimes for some specific task it may be easier to generate javascript on the fly in a bit complex way, like in rails rjs templates or jsonp responses.
However, with javascript libraries and approaches getting better and better, the need for this is becoming less, a simple example you may have needed to decide on a page whether to loop some elements and apply something or hide another single element, with jquery and other libraries, or even one's own function that handles some complex situation, you can achieve this with a simple condition and a call.
You know what I liked best about obtrusive javascript? You always knew what it was going to do when you triggered an event.
<a onclick="thisHappens()" />
Now that everybody's drinking the unobtrusive kool-aid it's not so obvious. Calls to bind events can happen on any line of any number of javascript file that get included on your page. This might not be a problem if you're the only developer, or if your team has some kind of convention for binding eventhandlers like always using a certain format of CSS class. In the real world though, it makes it hard to understand your code.
DOM browsers like Firebug seem like they could help, but it's still time consuming to browse all of an element's event handler properties just to find one that executes the code you're looking for. Even then it usually just tells you it's an anonymous function() with no line number.
The technique I've found for discovering what JS code gets executed when events are triggered is to use Safari's Profiling tool which can tell you what JS gets executed in a certain period of time, but that can sometimes be a lot of JS to hunt through.
There's got to be a faster way to find out what's happening when I click an element. Can someone please enlighten me?
Check out Visual Event... it's a bookmarklet you can use to expose events on a page.
If you're using jQuery you can take advantage of its advanced event system and inspect the function bodies of event handlers attached:
$('body').click(function(){ alert('test' )})
var foo = $('body').data('events');
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.
$.each( foo.click, function(i,o) {
alert(i) // guid of the event
alert(o) // the function definition of the event handler
});
Or you could implement your own event system.
To answer your question, try using the Firebug command line. This will let you use JavaScript to quickly grab an element by an ID, and then iterate through its listeners. Often, if used with console.log, you'll even be able to get the function definitions.
Now, to defend the unobtrusive:
The benefit I find in unobtrusive JavaScript is that it is a lot easier for me to see the DOM for what it is. That said, I feel that it is generally bad practice to create anonymous functions (with only few exceptions). (The biggest fault I find with JQuery is actually in their documentation. Anonymous functions can exist in a nether-world where failure does not lead to useful output, yet JQuery has made them standard.) I generally have the policy of only using anonymous functions if I need to use something like bindAsListener from Prototype.
Further, if the JS files are properly divided, they will only be addressing one sub-set of the DOM at a time. I have an "ordered checkbox" library, it is in only one JS file which then gets re-used in other projects. I'll also generally have all of the methods of a given sub-library as member methods of either a JSON object or a class and I have one object/class per js file (just as if I were doing everything in a more formalized language). If I have a question about my "form validation code", I will look at the formValidation object in formvalidation.js.
At the same time, I'll agree that sometimes things can become obtuse this way, especially when dealing with others. But disorganized code is disorganized code, and it is impossible to avoid unless you are working by yourself and are a good programmer.
In the end, though, I would rather deal with using /* */ to comment out most of two or three js files to find misbehaving code, then go through the HTML and remove the onclick attributes.
Calling it "kool-aid" seems unfair. DOM Level 2 events solve specific problems with inline event handling, like the conflicts that always result. I don't look back to writing code to use window.onload that has to check whether someone else has assigned it before, and sometimes having it overriden by accident or out of sloppiness. It also ensures a better separation of the structure (HTML) and behaviour (JS) layers. All in all, it's a good thing.
Regarding debugging, I don't think there's any way to solve the event handlers being anonymous functions, other than nagging the authors to use named functions where possible. If you can, tell them that it produces more meaningful call stacks and makes the code more maintainable.
One thing: you shouldn't be able to see what will happen in JavaScript by looking at the HTML code. What nuisance is that? HTML is for structure.
If you want to check what events are bound to certain elements, there's a bookmarklet called visual event for now, and firebug 1.6 (IIRC) will have some sort of event inspector.
The problem: I have a jQuery heavy page that has a built in admin interface. The admin functions only trigger when an admin variable is set. These functions require a second library to work properly and the second file is only included if the user is an admin when the page is first created. The functions will never trigger for normal users and normal users do not get the include for the second library.
Is it bad to reference a function does not exist in the files currently included even if that function can never be called? (does that make sense :)
Pseudocode:
header: (notice that admin.js is not included)
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="user.js"></script>
script.js: (admin functions referenced but can't be executed)
admin = false; // Assume this
$(".something").dblclick(function(){
if(admin)
adminstuff(); // Implemented in admin.js (not included)
else
userstuff();
});
Ideas:
I suppose two separate files for users and admins could be used but I feel that would be an overly complicated solution (don't want to maintain two large files with only a few lines of difference). The only reason I include a reference to the admin function in this file is I need to attach it to page elements that get refreshed as a part of the script. When jQuery refreshes the page I need to reattach function to interactive elements.
The Question:
I want to keep things very simple and not have to include file I don't have to if they will not be used by the user. Is this a good way to do this or should I be going another route?
The code should operate without error, since the admin functions without implementation will not be called. The only thing that is really being wasted is bandwidth to transmit the admin code that is not used.
However, let me caution against security through obscurity. If the user were to view this code and see that there are admin functions that they cannot access, they might get curious and try to download the "admin.js" file and see what these functions do. If your only block to keeping admin functions from being performed is to stop including the file, then some crafty user will probably quickly find a way to call the admin functions when they should not be able to.
If you already do server side authentication/permissions checking for the admin function calls just ignore my previous paragraph :-)
Personally, I would bind (or re-bind) the event in admin.js:
$(function() {
$(".something").dblclick(function(){
adminstuff();
});
});
function adminstuff()
{
// ...
}
That way, the adminstuff() call and the function will not be visible to "normal" users.
Good question. It shouldn't cause any JavaScript problems.
Other things to consider: you are potentially exposing your admin capabilities to the world when you do this, which might be useful to hackers. That's probably not much of a concern, but it is something to be aware of.
See also:
Why can I use a function before it’s defined in Javascript?
I don't think it matters. If it makes you feel better, you can make an empty stub function.
I don't think there's a dogmatic answer to this in my opinion. What you're doing is...creative. If you're not comfortable with it, that could be a sign to consider other options. But if you're even less comfortable with those then that could be a sign this is the right thing (or maybe the least wrong thing) to do. Ultimately you could mitigate the confusion by commenting the heck out of that line. I wouldn't let yourself get religious over best practices. Just be willing to stand by your choice. You've justified it to me, anyway.
Javascript is dynamic - it shouldn't care if the functions aren't defined.
If you put your admin functions in a namespace object (probably a good practice anyway), you have a couple of options.
Check for the existence of the function in the admin object
Check for the existence of the admin object (possibly replacing your flag)
Have an operations object instead, where the admin file replaces select functions when it loads. (Even better, use prototypical inheritance to hide them.)
I think you should be wary that you are setting yourself up for massive security issues. It is pretty trivial in firebug to change a variable such as admin to "true", and seeing as admin.js is publically accessible, its not enough to simple not include it on the page, as it is also simple to add another script tag to the page with firebug. A moderately knowledgeable user could easily give themselves admin rights in this scenario. I don't think you should ever rely on a purely client side security model.