Sunday, September 30, 2007

Getting browser's progress status

Ever wonder how to correctly get the page's progress of the browser (loading, transferring, waiting, etc)? Well here it is:

There are several states that can be detected using this interface
  • onStateChange
  • onLocationChange
  • onProgressChange
  • onStatusChange
  • onSecurityChange
  • onLinkIconAvailable
even though their names can seem self-explanatory, you better check the full documentation.

1) create an object that will withhold the Progress Listener Interface

var oProgressListener = new Object(); //on top of all codes, or with global scope


2) get the Progress Listener interface and assign preliminary values.

wpl = Components.interfaces.nsIWebProgressListener;

//I'm still not very sure what this function does :D
oProgressListener.QueryInterface = function(aIID) {
if (aIID.equals(oProgressListener.wpl) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports)) return this;
throw Components.results.NS_NOINTERFACE;

}


3) assign appropriate functions to the state you wants to:

//detect URL changes
oProgressListener.onLocationChange = function(aProgress, aRequest, aURI) {

alert('my URL was changed');
return 0;

}

//detect the starting of loading a new page / document
oProgressListener.onStateChange = function(aProgress, aRequest, aFlag, aStatus) {
if (aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT){
alert('New page is being loaded');
}
}

//detect when a page is fully loaded
if (aFlag & oProgressListener.wpl.STATE_STOP) {
if ( aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT ) {
alert('New page has finished loading');
}
}


4) Associate the progress listener for a "browser" to a listener object

browser.addProgressListener( oProgressListener,
Components.interfaces.nsIWebProgress.NOTIFY_STATE_WINDOW);

How to put log messages in Firefox's Error Console

Found out about how to add comments/logs to Firefox built-in Error Console. Really helps in debugging process.

1) get the Console Service component

var ConsSrv = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService);


2) write your logs!

ConsSrv.logStringMessage('here is my logs.. Hello!!!!');

Friday, September 21, 2007

Change multiple textbox value simultenously

Ever tried duplicating values from one main textbox to another (in XUL)? or to many others? Right after every keypresses from the user? Well, the JavaScript way is to call the onchange / onkeypress / onkeydown / onkeyup event for the main textbox, and when the event occurs, duplicate it's content to the target textboxes.

Well, this is not the same in case of XUL textboxes. Using onchange / onkeypress / onkeydown / onkeyup will always get the second latest char, as illustrated in this example:

Main textbox
-------------------------
| 12345 |
-------------------------

Duplicating textbox
-------------------------
| 1234 |
-------------------------

So the correct way is to use the oninput event handler, then you'll get the latest update from the main textbox.

Sample code:

<textbox id="main" oninput="duplicateValue()" />
<textbox id="duplicate" />

function duplicateValue()
{
var main = document.getElementById('main');
var duplicate = document.getElementById('duplicate');

duplicate.value = main.value;

}

Running multiple instances of firefox

Here is a very helpful article that elaborates (with pictures) on how to run multiple instances of Firefox(es) at the same time. This may be a requirement if you are trying to develop a Firefox extension and need to test it on 2 or more Firefox windows at the same time.

ref:
http://lifehacker.com/software/firefox/geek-to-live--manage-multiple-firefox-profiles-231646.php

Concatenating Object with String using eval()

eval() is a neat function that evaluates a string and executes it as if it was script
code.

Consider this code:

function displayItem(itemNo){
var item1 = "111";
var item2 = "222";
var item3 = "333";

eval("alert(item"+itemNo+")"); // the 'item' variable is concatenated with the parameter passed
}

and when call with this statement:

displayItem(1);

it will alert:

111

or in other case:

displayItem(3);

it will alert:

333

Getting X node value

Consider the following stanza:

<message>
<body>bar</body>
<x xmlns="myns">
<content>foo</content>
</x>
</message>

which is then passed to a function called getFoo(message), that will extract the value of <content>. I was having trouble getting that value using message.stanza.x.content, so I found an alternative way, by parsing the xml stanza through xml string.


What we need to do:


//declare a namespace var to make things easier...to read
ns = "myns";

//get the <x> node only
var x = message.stanza.ns::x;

//extracting the position value
var foovalue = loadXMLString(x);

//function to parse through XML String .. from w3schools.com
function loadXMLString(XMLtext)
{
//alert(XMLtext);
var parser=new DOMParser();
var doc=parser.parseFromString(XMLtext,"text/xml");

// documentElement always represents the root node
var x=doc.documentElement;

return x.childNodes[1].childNodes[0].nodeValue; //the <content> value..... Why so many childNodes? see below.


}

Why so many childNodes?

Even though the xml string we extracted (<x> node only) will be something like this:

<x xmlns="myns">
<content>foo</content>
</x>

In plain eyes, it looks like <x> have only 1 child node (content), but instead it has 3 nodes actually. The real stanza would be something like this:

<x xmlns="myns">
--- invisible textnode ---
<content>foo</content>
--- invisible textnode ---
</x>

you can prove this by displaying the nodeType for all the children:

x.childNodes[0].nodeType; // text
x.childNodes[1].nodeType; // element (<content>)
x.childNodes[2].nodeType; // text

ref:
http://www.w3schools.com/dom/dom_parser.asp
http://truetalkdev.blogspot.com/2007/06/sps-chat-events-stanzas.html

Tuesday, September 4, 2007

Get the previous sibling of a node

Consider this DOM tree:

<book>
<title>Magic Mayhem</title>
<author>Merlin</author>
<publisher>King Arthur Inc.</publisher>
</book>

and you would like to know who is the TITLE of the book, by passing the AUTHOR node to a function, i.e: getSibling(node); . You may use a handy function called element.previousSibling but there is matters to consider.

Must use a loop
The correct way (in IE & Mozilla) to get the previous sibling of a certain node is by using a loop that iterates through the child nodes:

function get_previoussibling(n)
{
//n = <author>
var x=n.previousSibling;
while (x.nodeType!=1)
{
x=x.previousSibling;
}
return x;
}

The nodeType = 1 will only be TRUE if the element is an element node (not a textnode or any other nodes). So the loop will keep on iterating until it find the correct element node (<title>) and returns that node. However, this may requires hevery processing when we have thousands of child nodes. Hence, if you are sure and know where is the place [index] of the child node you want, you may try this instead:

//n = <author>
var prevSibling = document.getElementById(n).parentNode.childNodes[0]; //returns <title> --- no loops required.

ref:
http://www.w3schools.com/dom/prop_element_previoussibling.asp

Detecting mouse over event

I was trying to register an event handler with a div's onmouseover event, there's something interesting that I found.

div.onmouseover = alert('yatta!');
- this event will be triggered every time the div is appended to another element (weird?), because u cant trigger a function with params with this statement.

div.setAttribute("onmouseover", "alert('yatta!');");
- this event will be triggered only when the mouse is over the div

Sunday, August 26, 2007

Load image from chrome

Previously, we load images from my googlepage. Now there's a faster way, that is, loading it from Chrome. What we need to do is just include this in chrome.manifest:

skin exte_name classic/1.0 chrome/skin/classic/

and load all images into the \chrome\skin\classic folder.

after that, we can simply load image using:

img.src = "chrome://exte_name/skin/image_name.jpg";

drawWindow can't grab flash videos?

drawWindow() is a handy function included with Mozilla's <canvas> tag. With it you can capture or grab the snapshot of what's in the content area of your browser.

Since it only takes snapshots, sometimes, it can grab flash video, but only after the video has finished loading. (proved by tabpreview) and will only get 1 frame of the video at 1 time, so will look awkward.

Setting online/offline to buddies

- able to get each incoming presence, using channel
- can't re-populate buddy list
- when disable channel and get presence only using xmpp.cache, it detects buddies on re-login only

-random development notes that relates to presence:
http://dev.hyperstruct.net/xmpp4moz/wiki/DocDevelopmentNotes

Monday, August 13, 2007

Checking whether windows has focus or not

- first... set focus on the window first with window.focus
- then.. add event listener to the window onblur event :
window.onblur = afunction()
- you're set!

Issues:
onBlur =
called when lost focus
onFocus =
called when got focus

There are 2 big areas that may clashes with focus, namely <window> and document <body>. Normally we want to detect when the user is not 'looking' at the browser window, maybe while doing work in MS Word. But if the last focus was given to the <body>, not <window>, even when you are looking at the browser window (but with a body element, such as a textbox is currently in focus), the onBlur event for window will be triggered.

Getting image width and height

- attach a function that gets the width and height of an image to the onload event for each images.
- once the images is finished loading, the function will be called, and we can get the values.
- 3 ways of attaching function to event:
myImage.setAttribute("onload", "getWH();");
myImage.onload = getWH;
myImage.addEventListener("load", getWH, true);

- we can pass parameters for the function only using the 1st method.
- loading animated gif requires longer time than still gif.

Image loaded directly inside browser, had no &lt;head&gt; tag

- try loading an image directly using a URL ending with image format extensions (.jpg, .png, .bmp)
- using DOM Inspector, try to view the hierarchy, there's no <head> tag !

Thursday, August 2, 2007

XEP-0104: HTTP Scheme for URL Data

XEP-0104: HTTP Scheme for URL Data

An article that relates to sending URLs inside xmpp stanza.

Animation-like behaviour in Javascript

I came across a website called Super Maryo World :D As you can figure out by its name, its another remake of the infamous Super Mario Bros. What catches my attention is that it's a game, created entirely in Javascript and can be played in the browser!

To satisfy my curiosity, I tried to somewhat try to code the character movements (move left, right and jump). It does requires some pretty tricky algo.

I was trying to move a div around. First I start of by some basic algo, which is:

OnPress Left
    Move Div Left by 10px

OnPress Right
    Move Div Right by 10px

OnPress Shift
    Move Div Up by 10px

Issues:
  • There's a 0.5 second pause after first movement of 10px, when pressing LEFT or RIGHT before the div continuously moving
  • You can only jump and move... by pressing UP, then DIRECTIONs, not by pressing DIRECTIONs first, then UP.
I'm not quite sure what is really the problem, but I do know that pressing keys may cause events to 'bubble' up (events are collected before it triggers). So it doesn't feels 'real'

Hence, inspired by ActionScript's onEnterFrame() method, a more realistic approach would be:

Use timer to create movements and jump 
OnPress Left
    startTimer To call MoveDiv(left)
       When timer expires, calls MoveDiv(left) recursively while pressing LEFT

OnPress Right
    startTimer To call MoveDiv(right)
       When timer expires, calls MoveDiv(right) recursively while pressing RIGHT

OnPress Shift
     startTimer To call MoveDiv(up)
       When timer expires, calls MoveDiv(up) recursively while pressing UP

and also you must put RETURN FALSE onkeypress ENTER key, to avoid unwanted auto-move bugs :D

Tuesday, July 31, 2007

Get the viewing plane .. correctly

As I've mentioned in previous post, we can use window.innerHeight to get the current viewing plane for the browser. However, since there are 2 documents inside a browser, putting them in either of them gave different values.

- reason:
- window.innerHeight called in Chrome level, return the browser's height
- window.innerHeight called in document level, return the viewpoint's height

- fixed using document.defaultView

This is a diagram taken from MDC:


#document
window main-window
...
browser
#document
window myExtensionWindow)

As you can see, since they are on different levels, calling window.innerHeight will gave different values. The higher <window> is the window for the whole browser, whereas the lower <window> is the window of the viewing plane.

get image size after image is fully loaded

If we need to get the size (width and height) of an image, in order to manipulate it, we first need to make sure that the image is fully loaded inside the web document. But at most time, we may not need to render the image, we just need the size. so here is a neat way to do this:

- using Image() object to load an image internally, without displaying the image in the doc, and then get the size.
function getWidthAndHeight() {
alert("'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.");
return true;
}
function loadFailure() {
alert("'" + this.name + "' failed to load.");
return true;
}
var myImage = new Image();
myImage.name = "someimg.jpg";
myImage.onload = getWidthAndHeight;
myImage.onerror = loadFailure;
myImage.src = "someimg.jpg";

With this code, the image is 'silently' being loaded into the current document. The image is attached with an 'onload' event listener, that calls a function named getWidthAndHeight() Note that onload event for images are only triggered after the image is fully downloaded to the browsers cache. So then, they will be no problem for us to get the correct size.

Thanks to phpnovice for his solution taken from webdeveloper.com

Detect when user resizes browser

There is a couple of ways to listens to the event triggered when a user resizes Firefox:

body.onresize
- when put an alert function for testing purpose, it alerts only once
- must be put inside loaded doc body, otherwise can't utilize 'body' var
- not valid HTML 4.0 spec

window.onresize
- alert twice
- can be put on chrome level or in document level
- valid HTML 4.0 spec

after some more tests:
- self.screen.availHeight = the whole screen height - taskbar height // not reliable
- window.innerHeight
- seems to be working accurately

Monday, July 23, 2007

XPCNativeWrapper : The DOM and Javascript Access Protector

During my search for solution for the previously mentioned problem, I stumbled upon a XPCNativeWrapper, a wrapper that wrap around DOMs and javascript codes, to protect if from XSS (Cross side server script) or unprivileged codes that may change the behavior of one's website or in Mozilla's case, the browser itself.

The praised functionality of a browser to allow DOM manipulation has make web-based and browser-based development more exciting. Yet, malicious codes will always try to do unethical thing, such as steal usernames and passwords as reported by Greasemonkey community.
Hence, a protector such as this is adequate.

Thanks to developers of Mozilla-based browsers, XPCNW has been enabled by default for Firefox version 1.5 and above.