Can we override the inbuilt functions in Javascript? - javascript

I have plenty of pages on my website with javascript embeded in them.
alert() which is a javascript function has been used in all my scripts atleast once. I want to use custom alert box which will render same in all the browser.
I can define my own function like
function customAlert()
{
// Code goes here.
}
But have to replace alert() withcustomAlert() in all my web pages which is a time consuming process.
Instead can't we just modify native alert function accordingly and it reflects the same as in all browsers.
I think we can't use this
function alert()
{
// Code goes here.
}
because alert is a reserved javascript word for function name.
If there is a better way for implementing the same with different technique, then feel free to answer.
I hate to use jquery or any other frameworks library so please answer regarding pure javascript.

The alert is a property of the global window object, thus you can override it in the following way:
window.alert = function (message){
//do your code
};
and then use it the way you used it before:
alert('hi');

Related

Don't understand Javascript function syntax

I'm looking through a website's source code because I'm trying to learn to some basic Javascript. I understand the first part:
function count() {
...
}
I know that the function is called count, and doesn't take any arguments. The next function I don't understand:
$(function(){
...
});
Is the function called 'function'? And why is there a '$' symbol at the beginning. I've tried searching the internet, but google just ignores the '$'s and brackets and just searches for 'function'.
In addition, another thing I don't understand; the website has a single button that, when pressed, plays an audio file. The button is set up like so:
<a href="javascript:void()" id="button">
<img src="img/button.png" border="0">
</a>
What does javascript:void() do?
I'm sorry this isn't really a programming question, but I'm trying to learn Javascript and i figured I might have a look what other people are doing.
$ is the name (actually a reference to) of a function defined by the very popular jQuery library.
$( ) is calling the $ function
Inside the parenthesis you have an anonymous function definition.
$(function(){ console.log('test'); });
is pretty much the same as:
function nameNotImportant() { console.log('test'); }
$(nameNotImportant);
but it's more concise and you don't have to think of a name for that function.
As you probably noticed, nameNotImportant is not called. A reference to it is passed as parameter to the $ function to do as it wants with it, including call it. That is exactly what the $ function does when passed a function as parameter to it: it calls that function when the DOM is ready to be interacted with.
<a href="javascript:void()">
When an <a>nchor is clicked, the default action performed by the browser is to navigate to its href attribute. If you want it to not do that, you have to somehow interfere with the mechanism, for example by setting the href attribute to execute some javascript code that does nothing. I wouldn't consider it an example of good programming, but that is what it is used for.
I'm assuming you know that $ is an alias to jQuery.
$(function() {
// ...
});
is passing an anonymous function to the $ function, which can take a callback function. This function is run when the DOM is ready, so the more verbose form of this is
$(document).ready(function() {
// ...
});
In addition,
javascript:void()
is used to simply return undefined for a URL--aka the browser does not navigate to a page when you click on the link. javascript:void() is often used to allow the developer to bind JavaScript click events to the <a> tag.

Why can't I access objects through the window object when using jQuery?

I'm trying to access a function through the window object. In my code, my function gets referred to by a string so I have to use the window object (or eval) to grab it. I tested out my code in pure JavaScript and it works perfectly. But when using jQuery it fails. Here is my test code:
function speak(words, callback){
for(var i=0;i<10000;i++){
console.log(words);
}
if(callback)
callback.call();
}
console.log(window['speak']);​
Here is a link to the pure JavaScript version which works.
Here is a link to the jQuery version which doesn't work.
What do I need to do to make this work in jQuery?
You didn't declare speak as a member of window, and JSFiddle actually wraps it in a document.ready callback. You'll need to explicitly set window.speak = speak as part of your code if you want it available on the window object.
Alternatively, you need to configure your fiddle to execute without a wrapper rather than onDomReady

javascript - how to call a function newly added from ajax

I have a coding difficulty which have been asked in this forum before:
Calling a JavaScript function returned from an Ajax response
But I didn't find the answers quite satisfying. To be more precise of the problem I'm dealing, here is the detail:
I dynamically load a document (HTML and javascript) using jquery
var url = 'document.php';
$('#container').load(url);
Example of what the document.php looks like:
<form>
<input name="firstname"></input>
</form>
<script>
function dosomething()
{
console.log($('input[name=firstname]').val());
}
</script>
*The dosomething() function is the one I'd like to call later
And then I want to call the functions from that document.php. Due to my requirement, I don't want to call the function after the documents' loaded, but rather to call it later when I need it. Because it was dynamically loaded, the DOM doesn't recognize the functions. How to properly call this function?
Thank you
the DOM doesn't recognize the functions
This sounds like your other functions are wrapped in $(document).ready() in the remote page. If that is the case they are out of scope for you to call them from code in the main page and you need to move them out of the ready handler to make them globally accessible.
EDIT: Other possibilities
Script tags in head- move to body after html, or use $.getScript in ajax callback to retrieve
I think that you're trying to implement the technique called on-demand javascript (or lazy-loading). In other words, your page should initially load just a small script - but use a bunch of objects and functions, which are available in some other files, but will be loaded when they're required.
If that's the case, I have to warn you: you'll probably need to update your existing code. Instead of just calling some function right as it is, in all gun-blazing glory, you should check for its existence first - and if it's not available, wait for its loading:
if (typeof lazyObjects.someLazyFunction !== 'function') {
lazyLoad('lazyFunction.js');
}
lazyObjects.someLazyFunction();
The key point here is that lazyLoad should be synchronous. In other words, you'll have to wait until the script containing your function is actually loaded. Otherwise someLazyFunction just won't be defined when it's called, even with this sort of checks.
lazyFunction.js, in turn, will contain some code that will alter lazyObjects, adding to them the required method as a property:
// in lazyFunction.js
lazyObjects.someLazyFunction = function() { ... }
While it's technically possible to use global (=window) object for these cases, I usually don't do this - and won't recommend doing it either.
See, it's not that simple. ) I'd recommend reading this article to find out more about this technique - and actually using some established components to implement it in your code (some of them are mentioned in the linked article).

Does a Javascript anonymous function remain visible? (Using a Java applet, a way to hide JS code)

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.

Pass a callback in ExternalInterface

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.

Categories

Resources