Fred
Brack Raleigh, NC |
This is not a full tutorial on the Browser Object Model (BOM) but rather an introduction and reference on how to use its basic features. I created this web page to help me document my understanding of the BOM as I progressed from novice to intermediate user ... and because I like to document stuff for others! I hope you find it useful.
The Browser Object Model (BOM) represents the browser in use as opposed to the HTML on the page. The Browser Object Model is how JavaScript communicates (reads and writes) with your browser. It has multiple components, such as information about the device in use, the physical screen, and the current window. While they are all part of the window object, the following subcategories exist: screen, location, history, navigator, popup alert, timing, and cookies. You can learn more about the Browser Object Model on the w3schools site, but we cover all the key elements here.
There are a number of browser methods which will return information about the browser being used, but some of them are pretty useless because they return the same information for almost every browser. Those we consider useless (and not shown below) are navigator.appName, navigator.appCodeName, navigator.product, navigator.platform, and navigator.appVersion. The method returning the most information about your browser is navigator.userAgent, but you will have to use a method like indexOf to find what you need. Here is what my Windows Firefox browser returned versus what my iPhone returned (as of September 2020):
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0 Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 [continued...] (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1
So here are the parts that navigator.userAgent returns:
A little vague, right? The official recommendation of Mozilla is not to rely on this field, as it can even be spoofed. However, it is used by some, and here's one example of how you can determine (in part) if the browser is on a mobile device (the other primary search field being "Android" of course):
browser = navigator.userAgent // See above two examples of output if (browser.indexOf("iPhone")!=-1) { iPhone=true };
Here is how you determine the URL currently in use:
// Window URL (location) information window.location.protocol // = ; the web protocol used (http: or https:) window.location.hostname // = ; the domain name of the web host window.location.pathname // = ; the path and filename of the current page // And finally the full href (URL) of the current page window.location.href // =
And if you need only the filename in use ...
var path = window.location.pathname; var slash = path.lastIndexOf("/"); filename = path.substr(slash+1); // =
There are various BOMs (Browser Object Model methods) that address the size of the current window or the computer's screen. This information might be valuable in determining how to present your data. Here are some of the methods as applied to your computer right now:
// current window size (height and width) in PIXELS window.innerHeight // = window.innerWidth // = // current screen size (height and width) in PIXELS screen.height // = screen.width // = // current screen available size (height and width) in PIXELS // this would minus interface features like the Windows task bar screen.availHeight // = screen.availWidth // =
Using BOM methods, you can open a URL in a new window, close the current window, or do things like resize a window.
newWindow = window.open(url); // opens the specified url in a new window
This method actually takes four operands, all of which are optional: window.open(url, target, specs, replace)
You can close either the current window or one you specifically opened, which is why in the example above we set the variable newWindow to the object name returned by window.open, so you could reference it later.
newWindow.close() // closes the window we opened above window.close() // closes the current window
A variation of the above method of opening a new window is the location.assign method. In this case, you are specifying where to go next in the current browser window, just the same as if you clicked a link; which means clicking the back button in the browser will return you to where you came from.
alert(location.assign("https://www.w3schools.com/jsref/met_loc_assign.asp"));
An alternate specification is location.replace, in which case the current document is removed from history and you cannot return to it. Instead, clicking the back button will take you to the next-previous location. This could be used, perhaps, as a form of redirect.
Speaking of "back," you can use history.back() or history.forward() to move forward or backwards in the history list.
Additional methods allow you to move a window (moveTo), resize it (resizeBy or resizeTo).
JavaScript has three kinds of popup boxes: an Alert box, a Confirm box, and a Prompt box. Technically, they are written with window. preceding their names, but that isn't required, so we will not show that.
alert("message"); // displays a message, and the user clicks OK alert("The answer is " + sum); confirm("message"); // user must click OK (returns true) or Cancel (returns false) confirm("Do you wish to continue?"); prompt("question text" [,"default value"]); // user's reply is returned when OK is pressed, // or null is returned if Cancel is pressed prompt("Enter your first name"); prompt("Enter number of iterations",10);
By the way, you can create multiline messages by using the special character \n for "new line" as follows:
alert("Here is the result of your search:\n"+searchResult); Here is the result of your search: There are 4 articles found written by Joe Jones.
Before we cover how to set or read cookies, you may want to know if your browser allows them. Note that all properties involving cookies use cookie, not cookies plural!
navigator.cookieEnabled // returns true or false // ... and in your case, the answer is
Also, before we go into the details, you need to know one important restriction about cookies: cookie values may not contain any control characters, whitespace (blanks, etc.), double quotes, comma, semicolon, or backslash. To protect against violating this rule, we should encode any cookie value on the way in and decode it on the way out. This is done with the methods encodeURIComponent and decodeURIComponent. In functions we offer below to read and write cookies, you will see this in practice. However, because in our simple up-front example we have a blank between first and last name, we will include the encoding. It may not be necessary (the browser might do this for us), but we'll try to set a good example here.
It turns out that you read and write cookies using the same property: document.cookie. It is an accessor property with native getter and setter functions. You write cookies one at a time, but they are read back all at once, and you must separate them yourself. When you write them, you must create a key=value pairing first, and you do not put quotes around the value. Example: Please note that if you copy and run this in your environment, you may find additional cookies returned first, and it will only work if cookies are enabled.
myCookie1 = "userid=fbrack"; // no blanks or special characters, so no encoding req'd myCookie2 = "user="+encodeURIComponent("Fred Brack"); // encodes as Fred%20Brack document.cookie = myCookie1; // write userid=fbrack document.cookie = myCookie2; // write user=Fred%20Brack var allCookies = decodeURIComponent(document.cookie); // return all cookies in string alert(allCookies); // = userid=fbrack; user=Fred Brack (which was decoded)
There are several additional operands available when setting a cookie, but we will just mention two of them: expiration date and the path to where the cookie should be stored. We only mention path because some browsers won't let you delete a cookie unless you specify the path; so it is a good habit to always specify path, even if it is the default value of the current directory (path=/), as typically is the case. The expiration date can be specified in one of two ways: max-age, specified in seconds; or expires, which is a date in a certain format.
Important: lf no expiration date is set, the cookie will be deleted when the browser closes!
And speaking of deleting a cookie, there is no cookie delete method. You delete a cookie by setting its expiration date to zero. Please include the path.
document.cookie = "userid=; max-age=0; path=/"
The most likely use for cookies is to check on a value, either to see if it exists or what it actually is. So a little help on that will be supplied here, courtesy of w3schools whose examples I have adapted! So first, a function to set a cookie, then one to get a cookie. Note: The expiration date is set by converting the number of days to seconds for max-age. Also note that the default path was established.
// Set the value of a cookie; specify cookie name, value, and expiration date in days function setCookie(cname, cvalue, exdays) { if (typeof(exdays)=="undefined" || exdays==="") { exdays = 1 } // default to 1-day cvalue = encodeURIComponent(cvalue); let expires = "max-age=" + exdays*86400; document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
In the example above, we set the cookie by combining the cookie name, an equals
sign, the cookie value, the expiration date converted from days to seconds, and
the default path.
// Get the value of a specified cookie; null if not found function getCookie(cname) { let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let cookieArray = decodedCookie.split(';'); for (var i = 0; i <cookieArray.length; i++) { let cookie = cookieArray[i]; while (cookie.charAt(0) == ' ') { cookie = cookie.substring(1) } if (cookie.indexOf(name) == 0) { return cookie.substring(name.length, cookie.length) } } return ""; }
Here is how to interpret the getCookie function's steps:
So using the getCookie function, we can locate our user and userid cookies that we wrote earlier. (Technically, of course, we should check to make sure a null value was not returned.)
var user = getCookie("user"); var userid = getCookie("userid"); alert("The userid for "+user+" is "+userid); // = The userid for Fred Brack is fbrack
w3schools offers this example showing how you could welcome a user back to your website.
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
# # # # #
Fred