I want to know how can we hide a function from the javascript console so that it can't be called from it.
To let you better understand the problem , suppose that I have a javascript function that adds some records on the database using Ajax, and anyone else can use this function from the console to add as many records as he wants on the database. I want the function to be called from the web application and not from the console... I tried to obfuscate the code to hide it but we can still find the function from Google Chrome javascript console.
No matter how much you obfuscate and hide your code, any javascript that can be executed on the client side can be executed in the console and you should always be running permissions/security checks on the server side if you wish to have any real control over the security of such functions.
That being said, you can restructure your code inside an immediately invoked function expression which will not be callable as easily from the console as usual like so:
(function() {
var myUncallableFunction = function() { alert('meow'); }
})();
the function myUncallableFunction will only be able to be called from within the parent function as it is a local variable to that parent function and is therefore inaccessible outside of it.
You will still be able to call this function inside of that parent however like so:
(function() {
var myUncallableFunction = function() { alert('meow'); }
myUncallableFunction();
})();
Related
Coming from a C++ background, trying to work with an OO language that doesn't have explicit typing is a little more than a headache.
So I have dynamic elements for a webpage that are "controlled" by objects since there are tons of stuff I need to manage on each for it to work. The element is just the visual output of the data inside of the object itself, that's all I really need it for.
Except that I need the object to perform an internal function when it's clicked. That seems to be the biggest source of my headache thus far.
Javascript:
function onClick(file) //The external onClick function I use to try to get it to call from.
{
file.state = INUSE;
file.checkState();
}
function fileObject () { //The file object itself
this.element;
this.newElement();
//initialize stuff for the object
}
fileObject.prototype.newElement = function() { //creates a new element and sets its event listener
this.element.click(function() {onClick(this)});
}
fileObject.prototype.checkState = function() {/*does stuff*/} //apparently this is "not a function"
The error I get exactly is "file.checkState is not a function" from Firefox's console panel.
I'm still new to javascript, but after doing some debugging, I've come to find out that it's explicitly the onClick(this) function that is causing all of the errors. When used with something else, the onClick function works perfectly, but for some reason, the this keyword doesn't appear to actually be sending the reference to the fileObject since all checks show file being undefined when inside of the onClick scope.
Is there something fundamentally wrong about the way I'm trying to do this or am I just missing a step (or adding something that I don't need) that will help get this snippet working.
So you know, your initial problem isn't actually handling the action, but listening to it. click will trigger a synthetic click event, rather than liste for one.
You want ... .element.addEventListener("click", callback); that said, you face a second problem, immediately thereafter.
I will leave my example code as you've written it to not confuse the matter...
But when you see click( ) know that I mean subscribing with addEventListener, if element really does mean a browser DOM element. If it's not a standard browser element, and your own API, then ignore the previous portion, and carry on.
this is dynamically bound at the invocation time of the function (not at definition time).
The nearest function, scoped above, is your callback function that you are passing into .click( ... ).
Which is entirely different than the this which you mean outside of the callback.
Whatever is on the left-hand side of the dot is the this context for the duration of that particular invocation.
Needless to say, click() doesn't know enough to bind the this you mean, to the left-hand side of your callback.
The solution (or one of many) is to use lexical scoping and/or closure to retain the value of the object you mean.
// easy but messier
var fileObject = this;
... .click(function () { onClick(fileObject); });
// Cleaner with thunks:
function clickHandler (onClick, obj) {
return function () { onClick(obj); };
}
... .click(clickHandler(this));
Coming from c++ the way Javascript handles this will seem a little crazy, it looks like here you need to tell the function you've defined what this is - like so:
this.element.click(function() {onClick(this)}.bind(this));
It keeps me from easily defining global variables and its often a nuisance. Why doesn't the code outside functions that are called execute? For example, if I call the function myFunction from HTML, this works...
function myFunction() {
var myObject = document.getElementById("myHTMLObject");
myObject.style.backgroundColor = "blue";
}
but not this...
var myObject = document.getElementById("myHTMLObject");
function myFunction() {
myObject.style.backgroundColor = "blue";
}
If I call the function from the HTML, only the code inside that function will run (unless that function calls other functions). Am I making a mistake or is there a way around this? I don't want to encompass all my code in a window.onload function.
P.S. I run my html on Chrome if it makes a difference.
Thanks for any help.
It does execute, and does when when the script runs, which is when the <script> element is parsed.
If you try to get an element that is added to the DOM by HTML that appears after the <script>, then it won't exist when you look for it so you will get nothing back.
If the <script> appears after the element, then you won't have a problem.
If this example:
var myObject = document.getElementById("myHTMLObject");
function myFunction() {
myObject.style.backgroundColor = "blue";
}
doesn't work, then here are a couple possible reasons:
The script is running too early and thus when you do document.getElementById("myHTMLObject");, the page has not yet been loaded and thus myHTMLObject does not exist yet.
You have more than one global definition of myObject and one is overwriting the other.
Your second coding example is recommended for a number of reasons:
Doesn't use a global variables which is advantageous (variables are private to within the function and can't create conflicts with any other code or be interfered with by any other code).
The functionality is entirely contained within the function
There are no timing related issues with when the initialization code is run because the DOM is searched only when the operation is about to be carried out.
Getting DOM objects when needed works better with dynamically added HTML.
A simple user, triggered operation is plenty fast getting a DOM object when needed.
I'm writing an application using Javascript. I'm searching for a way to hide my code and I suppose I've found one, using Java Applet.
Anyway, I think that should be possible only if js anonimous functions' code doesn't remain accessible in any way after it's been evaluated.
(function(){...}).call(obj)
Applets can get a reference to the browser's window they are in, and call its eval method to evaluate js code:
// java code
JSObject window = JSObject.getWindow(this);
window.eval( "(function(){"
+ ...
+ "}).call("
+ thisObjectName
+ ")" );
Thus, I can change my js code, in the way that some functions, instead of having their code inside, call an applet function that asks the window to eval the original js function code, passing to the window an anonimous function, so that no function reference remains. Of course, js function must give to java function the name of the object (the this), and java function must compose the anonimous function adding a call to the call(objectName) method, to use the this reference properly.
MyJsClass.prototype.func = function() { ... };
becames:
MyJsClass.prototype.func = function()
{
...
myApplet.evalJsCode(thisObjectName);
...
};
[UPDATE] My idea was not good for 2 reasons
Java bytecode (.class) is easy to de-compile (thanks to Pointy)
The window.eval function called by the Applet is the very same you can override via javascript (thanks to Yoshi)
Have you considered the following possibility?
​window.eval = function (code) {
console.log('code');
};
eval('alert(1)');
Meaning, it takes almost no effort overriding the eval function.
I want to call a Javascript function from Flash, which I can do with ExternalInterface, but the Javascript function takes a callback. Is there a way to give it a Flash callback?
I've thought of something like this:
ExternalInterface.addCallback("foo", function(){...});
ExternalInterface.call("theFunction", "foo");
But that wouldn't work since theFunction would attempt to do foo(), while it should really do swfObject.foo(). The problem is the page and its Javascript are not under my control (though I can request changes if really needed).
This is closely related to the first question in the related questions section.
Along the same lines as the answer to that question, you can do:
ExternalInterface.addCallback("foo", function() { /* ... */ }); // The callback
ExternalInterface.call("theFunction(function() { swfObject.foo(); })");
You're misunderstanding the documentation, I think. callback in this instance is just a reference to a function inside Flash, not a callback to something you call.
Basically, you use .call() to call a JS function from AS; and you use .addCallback() to tell the Flash Player which AS function should be called based on the name.
On your example, theFunction would get one parameter as being 'foo', which is the name that references your anonymous AS function. Not sure why you would want to pass the function like that, but if you need, you could just call it from JavaScript with
function theFunction(callback) {
// .. do something...
swfObject[callback]();
}
Now, if you don't have control over the JS/HTML side, I'm not sure if you can do that. Not sure why you'd need, anyway - JS calls are synchronous, as if they were running on the same thread, meaning the Flash Player will execute the JS code and only then return to the Flash Player... you don't have to wait for execution or anything.
Also, if you really need to control the page without touching the JS/HTML side, remember you can inject entire pieces of JS code via .call - it doesn't need to be a simple function call. You can create your entire functions from inside the SWF. For example,
var js:XML = <script><![CDATA[
// Javascript code...
]]></script>;
ExternalInterface.call(js);
Or, if you need the return data, you don't need a callback either - just do a simple call as in
// JS
function isNumberZero(__num) {
return __num == 0;
}
// AS
trace ("Is number zero = " + ExternalInterface.call("isNumberZero", 10));
Not sure if this helps at all. If not, it'd be good to have more information on what exactly you're trying to do.
I have a lengthy JavaScript file that passes JSLint except for "used before it was defined" errors.
I used normal function declarations, as in...
function whatever() {do something;}
as opposed to...
var whatever = function(){do something;};
and consistent with Steve Harrison's reply to an earlier post...
Assuming you declare all your
functions with the function keyword, I
think it becomes a programming-style
question. Personally, I prefer to
structure my functions in a way that
seems logical and makes the code as
readable as possible. For example,
like you, I'd put an init function at
the top, because it's where everything
starts from.
... I like seeing the functions in an order that makes sense to me.
The script functions perfectly in the several browsers tested (e.g., FireFox, Safari, Mobile Safari, Fennec, IE, Chrome, Midori, etc.).
Here's the problem: I want to use the script inside of an iPhone app being built with Titanium but its compiler stops with "used before defined" errors.
How can I get around this?
This might be a stupid question but also... If functions need to be called in a particular order, how does one resolve the matter of a called function needing to call back to the function that originally called it? For instance...
function buildMenu(){
Display a list of five menu items, each of which calls a function to build the associated screen.
}
function screen1() {
Display the screen associated with menu item #1.
}
If the functions need to be declared in order, function screen1 would need to precede function buildMenu. But what if, under certain conditions, screen1 cannot be built and hence wants to redisplay the menu (i.e., calling a function that is technically not yet declared)?
Oh yeah... one more question: Are there websites or programs that automatically re-sequence the functions rather than requiring the programmer to do it manually?
No, EM's answer is NOT the right solution. Try running this JavaScript:
(function () {
foo(); // right
var foo = function () {
console.log("wrong");
};
foo(); // wrong
function foo() {
console.log("right");
}
foo(); // wrong
}());
This is because the interpreter will first read the function declaration, create the name foo as a function that prints "right", then reads the var statement, and find that there is already a name foo so it will skip creating a new variable with the value undefined, as normally happens. Then it processes the code, line-by-line, which includes an assignment to foo. The function declaration does not get reprocessed. Maybe this will behave differently in Titanium, but try this in Firebug and you'll get what I got.
A better solution is:
var screen1, buildMenu;
screen1 = function () { buildMenu(); };
buildMenu = function () { screen1(); };
This will also pass JSLint, and produce the correct behavior.