In this lesson are presented the JavaScript level one browser objects: navigator and history.
1. navigator object
The navigator object gives some informations about what browser is running your code.
You can use it to collect data about what browsers visit your sites. For example, if you know that Internet Explorer doesn’t support some code, you can test:
if ( window.navigator.appName == "Microsoft Internet Explorer" ).
navigator object properties
- appCodeName - Returns the internal code name of the current browser.
- appName - Returns the official name of the browser.
- appVersion - Returns the version of the browser as a string.
- cookieEnabled - Returns a boolean (true or false) indicating whether cookies are enabled in the browser or not
- platform - Returns a string representing the platform of the browser.
- userAgent - Returns the user agent string for the current browser.
- The following example writes in the page the return values of these properties (used on Firefox).
<script type="text/javascript"><!--
document.write('appCodeName - '+ navigator.appCodeName+ '<br />');
document.write('appName - '+ navigator.appName+ '<br />');
document.write('appVersion - '+ navigator.appVersion+ '<br />');
document.write('cookieEnabled - '+ navigator.cookieEnabled+ '<br />');
document.write('platform - '+ navigator.platform+ '<br />');
document.write('userAgent - '+ navigator.userAgent+ '<br />');
--></script>
- The result is:
appCodeName - Mozilla
appName - Netscape
appVersion - 5.0 (Windows; en-US)
cookieEnabled - true
platform - Win32
userAgent - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
navigator object methods
- javaEnabled() - Indicates whether the host browser has Java enabled or not.
- taintEnabled() - Specifies whether or not the browser has data tainting enabled
- The following example writes a message about if Java is enabled or not.
<script type="text/javascript"><!--
if (navigator.javaEnabled) document.write('Java enabled');
else document.write('Java is not enabled');
--></script>
2. history object
The history object contains a list of URLs that the user visited within the current browser window and some features to navigate that list. It is part of the window object and is accessed through the window.history
history object properties
- length - Returns the number of URLs in the history list
- Example:
<script type="text/javascript"><!--
document.write(window.history.length); // 3
--></script>
history object methods
- back() - Moves back one in the window history (Same as pressing the Back button).
- forward() - Loads the next URL in the history list
- go(nr) - Loads a page from the session history, identified by its relative location (nr) to the current page.
- The fallowing example creates a button to go back two pages:
<script type="text/javascript"><!--
function goBack() {
window.history.go(-2);
}
--></script>
<button onclick="goBack()">Go Back 2</button>