Sunday, December 12, 2004

Using Javascript XMLHttpRequest object to connect to any hosts on Mozilla/Firefox

XMLHttpRequest is a great client-side Javascript API to create rich-client dynamic webpages. Being supported by both Mozilla/Firefox and Internet Explorer, you can dynamically feed a webpage with new contents without refreshing the page. This creates a much better user experience under many situations, especially on resource-extensive websites such as chatrooms or message boards.

For those who are unfamiliar with Javascript XMLHttpRequest, Jim Ley has written a very good introductory article here.

A common problem faced by Mozilla/Firefox Javascript developers is that, the browser's default security permission does not allow your XMLHttpRequest object to access any hosts other than the host where the script is originated from. For instance, when you access the script from http://www.foo.com/test.html, your XMLHttpRequest object can only make connections to www.foo.com but not any other hosts such as www.foo.com:81 or www.bar.com.

A solution to this is to request UniversalBrowserRead privilege from the browser:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

When Mozilla/Firefox runs this line, it will pop up a security dialog box asking the user to "Allow" or "Deny" this request. If the user clicks "Allow", your script will then be allowed to access any hosts.

Note, however, that this privilege is granted only within the scope of the function. If you use XMLHttpRequest on a different function, you must ask for permission again, like this:

function func1()
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); xmlhttp.open("GET", "http://www.bar.com/",true); xmlhttp.onreadystatechange = fx;
xmlhttp.send(null);
}

function func2()
{
// Ask again because the privilege is granted on a per-function basis
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); xmlhttp.open("GET", "http://www.bar2.com/",true); xmlhttp.onreadystatechange = fx;
xmlhttp.send(null);
}

For more information, please consult Mozilla's javascript security documentation here.

No comments: