↑
Main Page
location object
var oNewWin = window.open(“about:blank”, “newwindow”,
“height=150,width=300,top=10,left=10,resizable=yes”);
oNewWin.document.open();
oNewWin.document.write(“<html><head><title>New Window</title></head>”);
oNewWin.document.write(“<body>This is a new window!</body></html>”);
oNewWin.document.close();
This example opens a blank page (using the native
“about:blank”
URL) and then writes a new page to
it. To do this appropriately, the
open()
method is called before the using
write()
. After the writing is
complete,
close()
is called to complete the rendering. This technique is useful when you want to dis-
play a page without going back to the server.
The location object
One of the most useful objects in the BOM is
location
, which is a property of both
window
and
docu-
ment
(this is where a lack of standards leads to some real confusion). The
location
object represents
the URL loaded in a window and, as an added bonus, it also parses the URL into various segments:
?
hash
— If the URL contains a pound sign (
#
), this returns the content after it (for example,
http://www.somewhere.com/index#section1
has a hash equal to
“#section1”
).
?
host
— The name of the server (for example, www.wrox.com)
?
hostname
— Most often equal to
host
, this sometimes eliminates the
www.
from the front.
?
href
— The full URL of the currently loaded page
?
pathname
— Everything after the host in the URL. For example, the
pathname
for
http://www.somewhere.com/pictures/index.htm
is
“/pictures/index.htm”
.
?
port
— The port of the request if specified in the URL. By default, most URLs don’t include
the port as part of the URL so this property is typically blank. If a URL is used such as
http://www.somewhere.com:8080/index.htm
, the
port
is equal to 8080.
?
protocol
— The protocol used in the URL. This is everything before the two forward slashes
(
//
) in the URL. For example, the
protocol
for
http://www.wrox.com
is
http:
and the
protocol
for
ftp://www.wrox.com
is
ftp:
.
?
search
— Otherwise known as the query string, this is everything after a question mark (
?
)
in a URL performing a GET request. For example, the
search
for
http://www.somewhere
.com/search.htm?term=javascript
is
?term=javascript
.
The
location.href
property is used most often to either get or set the URL of the window (in this
regard, it is similar to
document.URL
). You can navigate to a new page just by changing its value:
location.href = “http://www.wrox.com/”;
When navigating this way, the new location is added to the history stack after the previous page, mean-
ing that the Back button goes to the page that made this call.
153
JavaScript in the Browser
08_579088 ch05.qxd 3/28/05 11:37 AM Page 153
Free JavaScript Editor
Ajax Editor
©
→