Info
- Javascript FAQ
Section
1: General JavaScript Info
- What
is JavaScript?
- What
is the goal of the JavaScript Newsgroup?
- Aren't
JavaScript and Java the same thing?
- What
browsers support JavaScript, and where can I find documentation?
- What
are the compatibility issues for the Netscape Developer?
- Where
is the current bug list for JavaScript?
- How do
I report a bug?
- What
differences exist between JavaScript versions?
- What
is the difference between Client-Side and Server-Side JavaScript?
1.1:
What is JavaScript?
JavaScript is a compact,
object-based scripting language for developing client and server Internet applications.
Netscape Navigator interprets Client-Side JavaScript statements embedded in
an HTML page. Server-Side JavaScript is compiled into platform-independent bytecode
and used by LiveWire (now part of Enterprise Server 3.0), enabling you to create
server-based applications similar to Common Gateway Interface (CGI) programs.
This FAQ describes the JavaScript language on the client, specifically its use
in Navigator. For information on developing server-based JavaScript applications,
see the LiveWire Developer's
Guide.
1.2:
What is the goal of the JavaScript Newsgroup?
The JavaScript Newsgroup
is established as a forum for developers to discuss hot topics, work out mutual
problems, and expand the overall knowledge and awareness of JavaScript. Discussions
range from the beginner who wants to open a new window to the advanced scripter
who wants to manipulate multiple frames in multiple windows. Compatibility issues
are also very common within the newsgroup.
1.3:
Aren't JavaScript and Java the same thing?
1.4:
What browsers support JavaScript, and where can I find documentation?
Both Netscape and MSIE support
JavaScript, with newer browsers supporting later versions of JavaScript:
1.5:
What are the compatibility issues for the Netscape Developer?
Trying to make the universally-compatible
script these days is almost pure folly. In order to support the broadest possible
audience, you should author code that is either sensitive to the browser that's
executing it, or code that uses only JavaScript 1.0, which is supported by most
browsers currently in use.
These sites contain
information that can help make your JavaScript as "browser-friendly" as possible:
1.6:
Where is the current bug list for JavaScript?
Although Netscape does have
an official Known Bugs
document for JavaScript, for the most updated and accurate information, please
try posting to the JavaScript
newsgroup.
1.7:
How do I report a bug?
DevEdge bug reports are
viewed directly by Netscape engineering teams and help identify problems in
shipping products and betas. It is suggested you view the various DevEdge newsgroups
prior to reporting a bug since identified problems (bugs) are often discussed
within the relevant newsgroups. A bug report
form is available for developers who wish to report new findings.
1.8:
What differences exist between JavaScript versions?
1.9: What is the difference between Client-Side and Server-Side JavaScript?
Client-Side JavaScript and
Server-Side JavaScript have been different, but now are unified as JS 1.2 in
Communicator 4.0 and ES 3.0. Client-Side JavaScript is interpreted only within
browsers that support it, and the code is visible to the user. Server-Side JavaScript
is stored in a pre-compiled state on the server, so it is browser-independent,
and only the results of the JavaScript programs are passed to the browser, so
that code is never revealed. There are also fundamental differences in the available
objects. An article written by Paul Dreyfus may be seen at View Source on the
DevEdge Web site that describes JavaScript
on the Server. Server-Side JavaScript is supported separately from client-side
JavaScript -- use the snews://secnews.netscape.com/netscape.dev.livewire.programming
and snews://secnews.netscape.com/netscape.dev.livewire.dbconfig
newsgroups, or the LiveWire
FAQ instead.
Back to the Question
Summary, or to the top.
Section
2: JavaScript Programming Basics
- How can
I use JavaScript to detect the browser type & version?
- Is JavaScript's
math inaccurate (0.119 * 100 = 11.899999)?
- How do
I do image "rollovers" (change the image when the mouse is over it)?
- How do
I use the different substring functions to extract part of a string?
- How do
I round numbers off to a certain number of decimal places?
- Why do
I have trouble with JavaScript within tables?
- Where
can I get information on Cookies?
- Why do
I sometimes see a URL beginning with wysiwyg?
- Problems
caching .js source files?
- Can
I detect the back button?
- What's
the difference between Grey and Gray?
- Why
doesn't document.lastModified work when I put my files
on a web server?
- Why
do I have trouble adding values in forms?
2.1:
How can I use JavaScript to detect the browser type & version?
By inspecting the navigator
object's properties. You should consult:
2.2:
Is JavaScript's math inaccurate (0.119 * 100 = 11.899999)?
It's not an issue of accuracy,
but rather of the way that JavaScript does math internally. Generally, you can
avoid any unexpected results by rounding the result of your calcuations to the
precision of the most precise number in your equation. In the example above,
you would get the correct answer if you rounded the output to three decimal
places.
2.3:
How do I do image "rollovers" (change the image when the mouse is over it)?
It's easier than you think.
Just use the onMouseOver and onMouseOut events to change the .src property
of the image. Note that images are named using the name= element of
the <image> tag:
<a href="home.html"> onMouseOver = "document.homeImage.src='homeLitUp.gif'; return true;"> onMouseOut = "document.homeImage.src='homeNormal.gif'; return true;"> <img name="homeImage" src="homeNormal.gif"> </a>
|
2.4:
How do I use the different substring functions to extract part of a string?
There are several ways of
selecting substrings in JavaScript, including substring(), substr(),
slice(), and the regexp functions.
In JavaScript 1.0 and
1.1, substring() exists as the only simple way to select parts of
a larger string. For example, to select the string press from Expression,
use "Expression".substring(2,7). The first parameter to the function
is the character index at which to start, while the second parameter is the
character index at which to end (non-inclusive): substring(2,7) includes
the indices 2, 3, 4, 5, and 6.
In JavaScript 1.2, substr(),
slice(), and the regexp functions can also be used to dissect
strings.
substr() behaves
in the same fashion that Perl's substr does, where the first parameter
indicates the character index at which to start, while the second parameter
indicates the length of the substring. To perform the same task as in the
previous example, "Expression".substr(2,5) can be used. Remember,
2 is the start point and 5 is the length of the resulting
substring.
When used on strings,
slice() behaves very similarly to the substring() function.
It is, however, a much more powerful tool, being able to operate on any type
of array, and not only on strings. slice() also makes use of negative
offsets to refer to a position taken from the end of the string rather than
the beginning. "Expression".slice(2,-3) will return the substring
found between the second letter and the letter third from the end, returning
press once more.
The final, and most versatile,
method for dealing with substrings is through the regular expression functions
in JavaScript 1.2. Once again, demonstrating with the same example, the substring
"press" is obtained from the string "Expression ":
write("Expression".match(/press/));
|
While this example is trivial,
the regexp documentation
is quite complete, providing more complex examples of the RegExp object
and its related functions.
2.5:
How do I round numbers off to a certain number of decimal places?
Use Math.round() to multiply
then number by ten times the number of decimal places you want to round off
by, then divide by that number.
For example:
var pi = "3.1415926535";
// Round to tenths:
pi = Math.round(pi*10)/10;
// Round to hundredths
pi = Math.round(pi*100)/100;
// etc...
|
2.6:
Why do I have trouble with JavaScript within tables?
2.7:
Where can I get information on Cookies?
Information on cookies can
be found in a wide range of places. Here are some examples:
2.8:
Why do I sometimes see a URL beginning with wysiwyg?
(What you see is what you
get!)
While working with client-side
JavaScript code, one might see URL's in the format: wysiwyg:/0/http://www.myserver.com/document.html.
These are internal references that are displayed in the location field and
are not troublesome in any way to either users or developers. The "0" in the
example is an internal document id, not a controllable parameter.
2.9:
Problems caching .js source files?
When reloading code that
sources data from .js files, Netscape clients frequently seem to become confused
and display the .js file as plain text on the HTML page instead of interpreting
the code contained within it.
Netscape clients prior
to version 3.01 are not actually affected by this problem as they do not cache
the .js source file at all, and so always assume .js files to contain JavaScript.
Beyond 3.01, the file is cached, and the given mime-type, not the extension
is later used in withdrawing the file from cache. If the mime-type is set
incorrectly by the server, then the .js file will be displayed as the type
text/plain.
To force the server to
accompany .js files with the correct mime type, find the mime.types file (or
equivalent) for the server and add this line: application/x-javascript
exts=js.
2.10:
Can I detect the back button?
Unfortunately, no! However,
the event handlers onBack and onForward are planned in a later version of Communicator.
2.11:
What's the difference between Grey and Gray?
Somehow, it seems that "lightgrey"
managed to squeeze through as the only British-spelled grey/gray colour. Odd.
Here's the complete grey/gray colour list:
darkgray
darkslategray
dimgray
gray
lightgrey **
lightslategrey
slategray
|
2.12: Why doesn't document.lastModified work when I put my
files on a web server?
Navigator expects to receive
the modification date of a file in the HTTP response header from the web server.
In the case of files that are being read from a local disk, Navigator is able
to get the modification date from the operating system.
Not all web servers
send the modification date along with the file. When viewing a file with a
call to document.lastModified on such a server, you'll get a meaningless
date.
2.13:
Why do I have trouble adding values to forms?
Form values are TEXT not
NUMBERS and therefore have to be converted to numbers first. Here are two ways
to do this.
varName = parseInt(document.formName.elementName.value, 10)
varName = document.formName.elementName.value - 0
In both cases varName
will contain the element value as a NUMBER.
Back to the Question
Summary, or to the top.
Section
3: Syntax
- Why do
the <script> container tags need to be enclosed inside comments?
- Is the LANGUAGE='JavaScript'
attribute required?
- Where
can <SCRIPT> container tags be placed within an HTML document?
- Are semicolons(;)required
at the end of all JavaScript statements?
- How can
I use quotation marks within a JavaScript statement?
- What
"scope" does a newly created variable have?
- What
does var do?
- Is there
any way to control the way a page prints using JavaScripts, can page breaks
be forced, etc.?
3.1:
Why do the <script> container tags need to be enclosed inside comments?
In a nutshell, for compatibility
with non-scriptable Web browsers. Potentially, the JavaScript code will be written
verbatim to the screen if comments are not used. Any Web browser that is termed
as being JavaScript-aware will scan the program code contained within the comments.
<script language="JavaScript">
<!--
alert("Hello, this is The DevEdge JavaScript Newsgroup");
//-->
</script>
|
3.2:
Is the LANGUAGE='JavaScript' attribute required?
The language attribute is
always recommended. Omitting the language tag will force the browser to use
its default scripting language, which may not be JavaScript. Furthermore, by
specifying a language attribute, you can custom-tailor your code on a scripting
language version-by-version basis.
3.3:
Where can <SCRIPT> container tags be placed within an HTML document?
3.4:
Are semicolons(;)required at the end of all JavaScript statements?
Semicolons are optional in
JavaScript statements that exist on separate lines. However, if you use statements
within event handling attributes (as part of a string) you will need to terminate
each statement with a semicolon.
<A HREF="http://www.mirana.com/page1.html" target="_top"
onMouseOver="window.status='Click here for page 1'; return true;"
onMouseOut ="window.status=''; return true;">Click Here!</a>
|
The semicolon is required
to separate the two JavaScript statements in the above example. Although semicolons
are optional, they are recommended both for debugging and readabilitiy reasons
and for consistency with other programming languages.
3.5:
How can I use quotation marks within a JavaScript statement?
Preface the quotation mark
with a backslash("\"). In fact, the backslash can be used before any character
to tell JavaScript to print it literally instead of using it as part of a statement.
For example:
<A HREF="http://www.mirana.com/pages/pages2.html" target="_top"
onMouseOver="window.status=\"Click Here for more pages \"; return true;"
onMouseOut ="window.status=\"\"; return true;">Click for more, here!</a>
|
3.6: What "scope" does a newly created variable have?
A variable created in JavaScript
is associated with a document loaded into the current browser window. The variable
appears to any code executing within the same document object scope (e.g. within
event handlers, functions, and code within the body). It's good to remember
that a variable created by your code is nothing more than a property of the
current document object. As such, it is not visible, to other frames that share
the same frameset, or other windows -- even those opened by the current document.
One way to overcome this
is to use a frameset document and define your variables within the 'parent'
document. In doing so the parent will always be in memory while the other
frames are used to load into them HTML documents, etc. Variables defined by
other documents are NOT global. Hence, in order to access a variable defined
in the another frame an appropriate expression must be used. The following
expression is an example:
parent.frames[n].document.variableName;
|
This also applies when the
window object has been used to open a window:
windowName.document.variableName
|
3.7:
What does var do?
Simply, var is used
within a function to create a variable that is local to that function.
For example:
function myFn() {
x = 5; // creates global variable x.
var y = 10; // creates local variable y (independent of global variable y).
var z = 20; // creates local variable z.
}
y = 1; // creates global variable y (independent of local variable y).
myFn();
// at this point (globally):
// x: 5;
// y: 1; <-- not 10!
// z: undefined
|
3.8: Is there any way to control the way a page prints using JavaScripts, can
page breaks be forced, etc.?
No. JavaScript does not expose
any control over how or what Netscape prints.
Back to the Question
Summary, or to the top.
Section
4: Frames & Windows
- Why does
document.write() open a new window instead of writing to the current one?
- How can
I load a frame without additional files?
- How do
I reference functions in a different frame?
- How do
I change two frames simultaneously with one click?
- How can
code in one frame determine if code in the other frames in my frameset have
finished loading?
- Why does
my call to window.open() not display the window type and size I specify?
- How can
I create a modal window (one that can't be minimized) using JavaScript?
- Can I
write JavaScript that will execute when the user closes a window?
- How can
I control the placement of a new window using window.open()?
- How
can I close a window without causing a confirm prompt to appear?
- I have
a pop-up window for a menu. How can my selections from this menu open documents
in a full size window?
- Can
I reuse the same pop-up window on different pages?
4.1: Why does document.write() open a new window instead of writing to the
current one?
This is, by far, the most
popular misunderstanding among JavaScript programmers.
Once the current document
has completed loading, you absolutely can not use document.write()
to modify its contents. The default behaviour of document.write(), once the
current document is done loading, is to open a new window of the type text/html,
and deliver your output to that window.
The rule to remember is
that the only opportunity you have to modify the display of the currently
loaded document object is:
- The contents of form
elements
- Document characteristics
that are exposed via the document object model (like bgcolor)
- Screen real estate
in which applets or plugins are running, and,
- Layers, which have
their own document object, and can thus be re-generated independent of your
script's document object.
4.2: How can I load a frame without additional files?
4.3: How do I reference functions in a different frame?
It is best to define functions
within a single document, parent frameset-document, meaning the HTML document
that defines the frameset(s). Then a function may be referenced by using the
following
parent.frameName.function();
|
You can also execute functions
in other frames by using the
windowReference.function()
|
syntax, but be aware of the
frame synchronization issues you'll face, as described below.
4.4: How do I change two frames simultaneously with one click?
The best way to do this is
to have a function that will do the dirty work for you:
function newPages() {
parent.frameA.document.location.href="http://.....";
parent.frameB.document.location.href="http://.....";
}
|
Then you call this function
via any object that supports an onClick event:
Note: If one of the pages
you wish to change is the one with this function in it, you should put a setTimeout()
on the command that changes the local page:
function newPages() {
parent.frameA.document.location.href="http://.....";
setTimeout('self.location.href="http://....."', 250);
}
|
This way all of your other
calls are executed before you close this page. Naturally, your specific needs
will differ, and this is only a suggestion.
4.5: How can code in one frame determine if code in the other frames in my
frameset have finished loading?
Often, while working with
multi-framed documents, it is necessary to access data in objects belonging
to sibling frames. It is conceivable that during the initial build of a frameset,
while the child frames are loading, frame A might request data from frame B
only to find that frame B has not finished loading or executing its code. This
synchronization problem often results in errors similar to "object has no property
indexed by zero" or "parent.frameB.variableName is undefined".
To resolve this, one can
implement onLoad handlers in the frameset so that any required cross-boundary
code is executed only after the entire document set is prepared:
frameset.html:
<frameset rows="50%,50%" onLoad="alert('Done the frameset')"> <frame name="frameA" src="frameA.html"> <frame name="frameB" src="frameB.html"> </frameset>
|
frameA.html:
<body bgcolor="white" onLoad="alert('Done A')"> </body>
|
frameB.html:
<body bgcolor="white" onLoad="alert('Done B')"> </body>
|
If all goes well, you'll
see the alerts from frame A, then B, then from the frameset, because the frameset
onLoad event handler files after all frames are done loading.
OnLoad Notes: Some
Netscape clients mistakenly call the frameset onLoad function before each
child document's onLoad function. In all Netscape clients with version numbers
less than 3.0, resizing the browser window generates an onLoad event -- not
always a desired action!
4.6: Why does my call to window.open() not display the window type and size
I specify?
It is important to note that
the third parameter to the window.open() function can contain no whitespace:
myWindow = window.open("http://www.netscape.com", "myWindowName",
"toolbar=yes,location=yes,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,height=400,width=600");
|
4.7: How can I create a modal window (one that can't be minimized) using JavaScript?
Using Navigator 2.x and
3.x:
<BODY onBlur="self.focus();">
|
Using a Communicator 4.x
signed script:
window.alwaysRaised = true; // Sets window to always on top
window.alwaysLowered = true; // Anchors window to desktop
|
4.8:
Can I write JavaScript that will execute when the user closes a window?
Not reliably. You can use
the onUnLoad event handler of the window object, but there's no guarantee that
your code will finish executing before Navigator 4 shuts down and cuts you off.
As of this writing, this was listed in the JavaScript
Known Bugs document.
You could, however, use
the onUnLoad event handler to execute code in another window, that presumably
isn't in the middle of closing, if you can be sure that the other window is
still open. This will be unreliable, at best.
This issue will presumably
be addressed in a future versions.
4.9: How can I control the placement of a new window using window.open()?
This is only possible using
Communicator 4.x, and is documented in What's
New in JavaScript 1.2 :
windowReference = window.open("document.html","windowName","screenX=20,screenY=30")
|
4.10: How can I close a window without causing a confirm prompt to appear?
The "close window" alert
will not appear if:
- The window you're
trying to close programmically was opened programmically by your script
or your script's document OR
- The window you're
trying to close is the first document loaded in that window (for example,
it was created by a link with a previously-unused target, or all
documents have been loaded in the window using location.replace()).
Using Navigator version
4 or later, a signed script with Universal Browser Write privileges can close
any window.
4.11
I have a pop-up window for a menu. How can my selections from this menu open
documents in a full size window?
In the head of the initial
HTML document put a window.name statement.
window.name="a_Name"
Then in the window open
statements in the menu use the same name.
varName = open("whatever.htm","a_Name","");
4.12 Can I reuse the same pop-up window on different pages?
Yes, use the same name each
time in the window open. The window size has to be the same.
varName = open("whatever.htm","same_Name","");
When you want to close the
pop-up put a window open just before the close.
varName = open("whatever.htm","same_Name","");
varName.close()
Back to the Question
Summary, or to the top.
Section
5: Forms
- How can
I use a select box as a navigation menu?
- How can
I use an image for a submit button?
- How can
I pass data between forms on different pages using JavaScript?
- Why doesn't
document.formName.selectObject.value reflect the value of the selected item
in the list?
- How do
I get the value of the currently selected radio button in a radio group or
group of checkboxes?
- How do
I get a form to submit with the Enter key?
- How can
I disable a text input field?
5.1: How can I use a select box as a navigation menu?
5.2: How can I use an image for a submit button?
Often, the question arises:
"How does one submit a form with an image, not a submit button?" The solution
is as simple as this example shows:
<form>
<input type="image" name="cancel" src="cancel.gif" alt="Cancel!" border=0>
<input type="image" name="continue" src="continue.gif" alt="Click to Continue" border=0>
</form>
|
When either button is clicked,
the form is submitted, and the x/y coordinates of the mouse click on the button
are loaded into the request object. For example, if the user had selected
Cancel!, the request object would contain cancel.x
and cancel.y variables. Similarly, a click on Continue, would
have resulted in continue.x and continue.y variables.
What is important to note
here is that the .x and .y elements are not variables on
a continue or cancel object but are actually part of the
name: "continue.x ". Consequently, one cannot use the typical method
for determining the existence of one of the request object's children:
if (request.normalItem)
act();
if (request.continue.x) // Noooo! Produces horrible error messages!
doContinuingThings();
|
However, consider this:
if (request['normalItem'])
act();
if (<B>request['continue.x']</B>) // Much better :)
doContinuingThings();
|
Thanks to JavaScript's named
arrays, it is possible to check which image submitted the form.
For some applications,
it is useful to know the coordinates of the cursor on the image clicked. That
information, of course, is contained in the image_element.x and image_element.y
pairs. The following Server-Side JavaScript could be used to detect
this::
x=0;
y=0;
if ((request['my_submit_image.x']) (request['my_submit_image.y'])) {
x = parseInt(request['my_submit_image.x']);
y = parseInt(request['my_submit_image.y']);
}
|
5.3: How can I pass data between forms on different pages using JavaScript?
This addresses the issue
of maintaining state between various forms.
As a simple example, suppose
you a 'home' page to ask a user for his name, then use that name to refer
to the user on later pages. You can collect the name using a form, then use
JavaScript to pass the username to the next page using a decorated URL. The
subsequent page could then parse the username out of the URL using the information
in document.search .
home.html
<html> <head> <script language="JavaScript">
function nextPage() {
self.location = "next.html?name=" + escape(document.theForm.userName.value);
// Use escape() any time there might be spaces or
} // non-alpa characters
</script>
</head>
<body>
<form onSubmit = "nextPage();return false;">
Enter your name: <input type=text name=userName>
<input type=submit>
</form>
</body>
</html>
|
next.html
userName = document.search;
userName = userName.substring(userName.indexOf("=")+1) // Get rid of 'name='
document.write("Greetings, " + userName + "<P>");
|
5.4: Why doesn't document.formName.selectObject.value reflect the value of
the selected item in the list?
Because that's not the way
the object works. The correct and complete syntax for accessing the VALUE
of the currently SELECTED item in a list is:
document.form.selectObject[document.form.selectObject.selectedIndex].value
5.5: How do I get the value of the currently selected radio button in a radio
group or group of checkboxes?
. There is a property created
in the form object for each set of radio buttons or checkboxes with
the same name. For example, the following HTML code:
<form name='theForm'>
<input type=radio name="gender" value="Male">Male
<input type=radio name="gender" value="Female">Female
<input type=radio name="gender" value="Evasive">Not Specified
</form>
|
results in the creation of
a 3 element array referenced by document.theForm.gender. In order to
determine the value of the presently selected button (or checkbox), you'll need
to examine each elements checked property. For example:
function checkIt() {
theGroup = document.theForm.gender;
for (i=0; i<= theGroup.length; i++) {
if (theGroup[i].checked) {
alert("The value is " + theGroup[i].value);
break;
}
}
}
|
5.6:
How do I get a form to submit with the Enter key?
Netscape will submit a form
if the enter key is pressed while the only text input element of the form has
the focus. You can affect simliar behavior in a form with more than one element
by breaking the form into a number of separate forms, so that each form has
only one text element. Use the onSubmit event handler (or action="javascript:myFunction(
);") to gather the data from the other forms in your page and submit it
all at once.
5.7:
How can I disable a text input field?
Use the onfocus handler to call the blur() function:
<INPUT TYPE="text" NAME="aTextField" ONFOCUS="this.blur()">
|
If you want to disable/enable
dynamically use function skip (e)
{ this.blur(); }
<A HREF="javascript:document.formName.aTextField.onfocus = skip; void
0">disable text field</A>
<A HREF="javascript:document.formName.aTextField.onfocus = null; void
0">enable text field</A>
|
Back to the Question
Summary, or to the top.
Section 6: JavaScript Security
- What
is a signed script?
- Access
disallowed from scripts at one.ingenia.com to documents
at two.ingenia.com?
- Why aren't
I able to read the URL history using the history object?
6.1: What is a signed script?
A signed script is a script
which has a digital signature associated with it, and which can therefore request
additional privileges from the user. Each privilege has a distinct name, such
as "UniversalBrowserWrite" -- allowing almost total control over the browser's
behaviour -- or "UniversalBrowserRead" -- allowing the script to read data from
other pages, preferences and so forth. There is information about using signed
scripts at http://developer.netscape.comhttp://developer.netscape.com/docs/manuals/communicator/jssec/index.htm.
The section on "codebase principals" may be of special interest to intranet
developers and others who wish to allow privileges to be requested without the
hassle of signatures. Danny Goodman's article at http://developer.netscape.com/news/viewsource/goodman_sscripts.html
is also recommended reading.
6.2: Access disallowed from scripts at one.ingenia.com to documents
at two.ingenia.com?
This error message indicates
that a section of JavaScript code is attempting to access properties that it
does not own. For example, imagine a framed document containing two pages: "http://one.ingenia.com/page1.html
" and "http://two.ingenia.com/page2.html
". If otherLocation = parent.page2.location.href was to be executed
by the first page, the Access Disallowed error would result, as page1.html
is trying to get information from two.ingenia.com to one.ingenia.com.
Please see the relevant
section of the Netscape JavaScript
Guide for more information on using
data tainting for security .
6.3:
Why aren't I able to read the URL history using the history object?
Unless your script is signed,
or operating with privileges granted by codebase principals, JavaScript only
allows you to access URL history of entries within the current domain. Check
the references in first section, above, for more information.
Back to the Question
Summary, or to the top.
Section
7: LiveConnect Techniques
- How can
I change the user's preferences using JavaScript?
- How can
I make Socket calls in JS?
- Can I
use JavaScript to read the source of an HTML page?
7.1: How can I change the user's preferences using JavaScript?
You can use LiveConnect to
communicate with Navigator:
netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesRead');
var home = navigator.preference('browser.startup.homepage');
if (home != 'http://www.someserver.com/') {
netscape.security.PrivilegeManager.enablePrivilege('UniversalPreferencesWrite');
navigator.preference('browser.startup.homepage','http://www.someserver.com/');
}
|
The Communicator Preferences document describes the names and functions of the
different preferences.
7.2:
How can I make Socket calls in JS?
Use this code as an example
which writes a http get request and reads the http status returned:
function fetchHTTPStatus (url) {
if ((location.host == '') || (url.indexOf(location.host) == -1))
netscape.security.PrivilegeManager.enablePrivilege('UniversalConnect');
var urlObj = new java.net.URL (url);
var host = urlObj.getHost();
var port = (urlObj.getPort() > 0) ? urlObj.getPort() : 80;
var fileName = urlObj.getFile();
var sock = new java.net.Socket (host, port);
dock = new java.io.DataOutputStream(sock.getOutputStream());
dock.writeBytes('GET ' + fileName + ' HTTP/1.0\r\n'); // could use
HEAD
dock.writeBytes('\r\n');
var dis = new java.io.DataInputStream(sock.getInputStream());
line = dis.readLine(); // get just status message
dis.close();
dock.close();
sock.close();
return line;
}
// example call
alert(fetchHTTPStatus('http://www.someserver.com/someUrl.html'))
alert(responseInt)
|
7.3: Can I use JavaScript to read the source of an HTML page?
function fetchURL(url) {
if ((location.host == '' && url.indexOf(location.protocol) == -1)
||
url.indexOf(location.host) == -1)
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalConnect");
}
var dest = new java.net.URL(url);
var dis = new java.io.DataInputStream(dest.openStream());
var res = "";
while ((line = dis.readLine()) != null) {
res += line;
res += java.lang.System.getProperty("line.separator");
}
dis.close();
return res;
}
//example call
alert(fetchURL(location.href));
}
|