Browser Object Model (BOM) allows JavaScript to "talk to" the browser
window - represents browser window
all global JavaScript objects, functions, and variables automatically become members of the window object
global variables are properties of the window object
global functions are methods of the window object
document object (of the HTML DOM) is a property of the window object: window.document.getElementById("header") is the same as document.getElementById("header")
browser window (the browser viewport) is NOT including toolbars and scrollbars
properties
self - current window
parent - parent window of the current window
opener - reference to the window that created the window
top - topmost browser window
name - sets or returns the name of a window
status - sets or returns the text in the statusbar of a window
defaultStatus - sets or returns the default text in the statusbar of a window
closed - whether a window has been closed or not
screen - Screen object for the window
history - History object for the window
console - reference to the Console object
document - Document object for the window
location - Location object for the window
navigator - Navigator object for the window
performance - Performance object, which can be used to gather performance information about the current document
crypto(window.crypto||window.msCrypto) - Crypto object associated to the global object, allows web pages access to certain cryptographic related services
localStorage
sessionStorage
innerWidth - width of a window's content area (viewport) including scrollbars
innerHeight - height of the window's content area (viewport) including scrollbars
outerWidth - width of the browser window, including toolbars/scrollbars
outerHeight - height of the browser window, including toolbars/scrollbars
devicePixelRatio - ratio of pixel sizes: the size of one CSS pixel to the size of one physical pixel
pageXOffset|scrollX - pixels the current document has been scrolled (horizontally) from the upper left corner of the window
pageYOffset|scrollY - pixels the current document has been scrolled (vertically) from the upper left corner of the window
screenTop - vertical coordinate of the window relative to the screen
screenLeft - horizontal coordinate of the window relative to the screen
screenX - horizontal coordinate of the window relative to the screen
screenY - vertical coordinate of the window relative to the screen
frameElement - iframe element in which the current window is inserted
frames - returns all iframe elements in the current window
length - number of iframe elements in the current window
methods
alert() - displays an alert box with a message and an OK button
prompt() - displays a dialog box that prompts the visitor for input
confirm() - displays a dialog box with a message and an OK and a Cancel button
open() - opens a new browser window
close() - closes the current window
stop() - stops the window from loading
focus() - sets focus to the current window
blur() - removes focus from the current window
print() - prints the content of the current window
resizeBy(plus_w,plus_h) - resizes the window by the specified pixels
resizeTo(w,h) - resizes the window to the specified width and height
scrollBy(x,y) - scrolls the document by the specified number of pixels
scrollTo(x,y) - scrolls the document to the specified coordinates
moveBy(x,y) - moves a window relative to its current position
moveTo(x,y) - moves a window to the specified position
setTimeout() - calls a function or evaluates an expression after a specified number of milliseconds
setInterval() - calls a function or evaluates an expression at specified intervals (in milliseconds)
clearTimeout() - clears a timer set with setTimeout()
clearInterval() - clears a timer set with setInterval()
requestAnimationFrame() - requests the browser to call a function to update an animation before the next repaint
atob() - decodes a base-64 encoded string
btoa() - encodes a string in base-64
getComputedStyle(el [,pseudoEl]) - gets the current computed CSS styles applied to an element
getSelection() - Selection object representing the range of text selected by the user
matchMedia(css_MQString) - MediaQueryList object representing the specified CSS media query string
properties: matches and media
methods: addListener(functionref) and removeListener(functionref)
canvas can appear too blurry on retina screens, window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image
Current window
window_checks
w_current
w_parent
this window
new window
var myWindow,
wtr = document.getElementById("window_test_result");
function openWin() {
"http://web-engineer-book/js-browser.html#window",
"myWindow",
"width=250, height=250"
);
}
function checkWin() {
if (!myWindow) {
wtr.innerHTML = "myWindow has never been opened!";
} else {
if (myWindow.closed) {
wtr.innerHTML = "myWindow has been closed!";
} else {
wtr.innerHTML = "myWindow has not been closed!";
}
}
}
function closeWin(){ if(myWindow){ myWindow.close(); } }
function resizeWinTo() {
myWindow.resizeTo(800, 600); myWindow.focus();
}
function resizeWinBy() {
myWindow.resizeBy(-100, -50); myWindow.focus();
}
function moveWinTo() {
myWindow.moveTo(150, 150); myWindow.focus();
}
function moveWinBy() {
myWindow.moveBy(75, 50); myWindow.focus();
}
function scrollWin(x, y) {
window.scrollBy(x, y);
}
function scrollWinTo(x, y) {
window.scrollTo(x, y);
}
var wc = document.getElementById("window_current");
var wp = document.getElementById("window_parent");
var w_current = window.self;
var w_parent = window.parent;
var w_checks = document.getElementById("window_checks");
function windows_tests() {
wc.innerHTML = "w_current.name = " + w_current.name +
"w_current.status = " + w_current.status +
// .....
"w_current.location = " + w_current.location;
wp.innerHTML = "w_parent.name = " + w_parent.name +
"w_parent.status = " + w_parent.status +
// .....
"w_parent.location = " + w_parent.location;
w_checks.innerHTML = "";
if (window.matchMedia("(max-width: 700px)").matches) {
w_checks.innerHTML += "viewport width <= 700 pixels";
} else {
w_checks.innerHTML += "viewport width > 700 pixels";
}
w_checks.innerHTML += "this box width: " +
window.getComputedStyle(w_checks, null).getPropertyValue("width");
var str = "Hello World!";
var enc = window.btoa(str);
var dec = window.atob(enc);
w_checks.innerHTML += "Encoded String: " + enc + "Decoded String: " + dec;
w_checks.innerHTML += "text selection (window.getSelection()):" + window.getSelection();
w_checks.innerHTML += "selections count: " + window.getSelection().rangeCount;
}
setInterval(windows_tests,200);
// matchMedia listeners
function matchMediaFunction(x) {
if (x.matches) { // If media query matches
document.body.style.backgroundColor = "yellow";
} else {
document.body.style.backgroundColor = "pink";
}
}
var x = window.matchMedia("(min-width: 700px)")
matchMediaFunction(x) // Call listener function at run time
x.addListener(matchMediaFunction) // Attach listener function on state changes
all computed styles of an object
cssObj = window.getComputedStyle(elem, null)
for (i = 0; i < cssObj.length; i++) {
cssObjProp = cssObj.item(i)
txt += cssObjProp + " = " + cssObj.getPropertyValue(cssObjProp);
}
// computed styles of a first letter (usage of pseudo element)
// window.getComputedStyle(elem, "first-letter").getPropertyValue("font-size");
screen.*
screen object contains information about the visitor's screen
properties
availWidth - width of the screen (excluding the Windows Taskbar)
availHeight - height of the screen (excluding the Windows Taskbar)
width - total width of the screen
height - total height of the screen
colorDepth - bit depth of the color palette for displaying images
pixelDepth - color resolution (in bits per pixel) of the screen
orientation - current orientation of the screen (instance of ScreenOrientation)
properties
type
angle
methods
lockOrientation(orientation) - locks the screen into the specified orientation
default
landscape
portrait
portrait-primary
portrait-secondary
landscape-primary
landscape-secondary
unlock() - unlocks the orientation of the containing document from its default orientation
window.location(or simply location) object can be used to get the current page address (URL) and to redirect the browser to a new page
properties
protocol - sets or returns the protocol of a URL
hostname - sets or returns the hostname of a URL
port - sets or returns the port number of a URL
origin - returns the protocol, hostname and port number of a URL
href - sets or returns the entire URL (absolute, relative, to an anchor, protocol(ftp://|mailto:|file://))
host - sets or returns the hostname and port number of a URL
pathname - sets or returns the path name of a URL
hash - sets or returns the anchor part (#) of a URL
search - sets or returns the querystring part of a URL
methods
reload([forceGet]) - reloads the current document (same as the reload button), forceGet - specifies the type of reloading: false(default) - reloads the current page from the cache, true - reloads the current page from the server
assign() - loads a new document
replace() - replaces the current document with a new one (it is not possible to navigate "back" to the original document)
most browsers will not display default port numbers (80 for http and 443 for https)
history object contains the URLs visited by the user (within a browser window)
properties
length - number of URLs in the history list
maximum length is 50
IE and Opera start at 0, while Firefox, Chrome, and Safari start at 1
returns at least 1, because the list includes the currently loaded page
property is useful to find out how many pages the user has visited in the current browsing session
read-only
state - state of the current history entry
methods
back() - loads the previous URL in the history list, equivalent to history.go(-1)
forward() - loads the next URL in the history list, equivalent to history.go(1)
go(number(-1|1|-3|...)|URL) - loads a specific URL from the history list
pushState(state_obj,title,URL) - add history entries
state object can be anything that can be serialized (if over 640k, use *Storage), associated with the new history entry, whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object
never causes a hashchange event to be fired, even if the new URL differs from the old URL only in its hash
new URL can be any URL in the same origin as the current URL. In contrast, setting window.location keeps you at the same document only if you modify only the hash
you don't have to change the URL if you don't want to. In contrast, setting window.location = "#foo"; creates a new history entry only if the current hash isn't #foo
you can associate arbitrary data with your new history entry, with the hash-based approach, you need to encode all of the relevant data into a short string
if title is subsequently used by browsers, this data can be utilized (independent of, say, the hash)
replaceState(state_obj,title,URL) - modifies the current history entry instead of creating a new one
doesn't prevent the creation of a new entry in the global browser history
useful when you want to update the state object or URL of the current history entry in response to some user action
AJAX navigation
include/*
<!-- include/header.php -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="../js/ajax_nav.js"></script>
<link rel="stylesheet" href="../css/style.css" />
<!-- include/before_content.php -->
<p>
<a class="ajax-nav" href="first_page.php">First example</a>
<a class="ajax-nav" href="second_page.php">Second example</a>
<a class="ajax-nav" href="third_page.php">Third example</a>
<a class="ajax-nav" href="unexisting.php">Unexisting page</a>
</p>
<!-- include/after_content.php -->
<p>This is the footer. It is shared between all ajax pages.</p>
first_page.php , ...
<?php
$page_title = "First page";
$as_json = false;
if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
$as_json = true;
ob_start();
} else {
?>
<!doctype html>
<html>
<head>
<?php
include "include/header.php";
echo "<title>" . $page_title . "</title>";
?>
</head>
<body>
<?php include "include/before_content.php"; ?>
<p>This paragraph is ...</p>
<div id="ajax-content">
<?php } ?>
<p>This is the content of <strong>first_page.php</strong>.</p>
<?php
if ($as_json) {
echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
} else {
?>
</div>
<p>This paragraph is ...</p>
<?php
include "include/after_content.php";
echo "</body>\n</html>";
}
userAgent - user-agent header sent by the browser to the server
appName - name
appCodeName- code name
appVersion - version information
product - engine name
language - language of the browser
languages - array of DOMStrings representing the user's preferred languages
platform - for which platform the browser is compiled
oscpu - string that identifies the current operating system
cookieEnabled - whether cookies are enabled
javaEnabled() - whether or not the browser has Java enabled
geolocation - Geolocation object that can be used to locate the user's position
onLine - whether the browser is online
connection - NetworkInformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered
properties
downlink - effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds
downlinkMax - maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology
effectiveType - effective type of the connection meaning one of slow-2g|2g|3g|4g, value is determined using a combination of recently observed round-trip time and downlink values
rtt - estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds
type - type of connection a device is using to communicate with the network, one of the following values: bluetooth|cellular|ethernet|none|wifi|wimax|other|unknown
events
onchange - connection information changes and the change is fired on this objec
methods (inherits from EventTarget)
storage - StorageManager object used to access the overall storage capabilities of the browser for the current site or app
deviceMemory - amount of device memory in gigabytes, given by rounding to the nearest power of 2 and dividing that number by 1024
hardwareConcurrency - number of logical processors available to run threads on the user's computer
serviceWorker - ServiceWorkerContainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the ServiceWorker
mimeTypes - MimeTypeArray object, list of MIME types recognized by the browser
mediaCapabilities - MediaCapabilities object that can expose information about the decoding and encoding capabilities for a given format and output capabilities as defined by the Media Capabilities API
mediaDevices - MediaDevices object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing
activeVRDisplays - array containing every VRDisplay object that is currently presenting (VRDisplay.ispresenting is true)
maxTouchPoints - maximum number of simultaneous touch contact points are supported by the current device
plugins - PluginArray object, listing the Plugin objects describing the plugins installed in the application
locks - LockManager object which provides methods for requesting a new Lock object and querying for an existing Lock object
request(var promise = name[, {mode:exclusive|shared, ifAvailable:false, steal:false, signal:AbortController.signal}], callback) - requests a Lock object with parameters specifying its name and characteristics, requested Lock is passed to a callback, while the function itself returns a Promise that resolves with undefined
query() - returns a Promise that resolves with a LockManagerSnapshot which contains information about held and pending locks
permissions - Permissions object that can be used to query and update permission status of APIs covered by the Permissions API
query(PermissionDescriptorObj) - state of a user permission on the global scope for a given API via Object:
userVisibleOnly : (Push only, not supported in Firefox, false), whether you want to show a notification for every message or be able to send silent push notifications
sysex : (Midi only, false) whether you need and/or receive system exclusive messages
request() - equests permission to use a given API. This is not currently supported in any browser
revoke() - revokes the permission currently set on a given API
credentials - CredentialsContainer interface, which exposes methods to request-credentials and notifies the user agent when an interesting event occurs, such as a successful sign-in or sign-out, can be used for feature detection
doNotTrack - user's do-not-track setting = 1 if the user has requested not to be tracked by web sites, content, or advertising, use window.doNotTrack for IE/Edge
usb
methods
sendBeaconurl [,ArrayBufferView|Blob|DOMString|FormData]) - can be used to asynchronously transfer a small amount of data over HTTP to a web server
vibrate(pattern) - pulses the vibration hardware on the device, if such hardware exists. If the device doesn't support vibration, this method has no effect. If a vibration pattern is already in progress when this method is called, the previous pattern is halted and the new one begins instead
"Netscape" is the appName for both IE11, Chrome, Firefox, and Safari
"Mozilla" is the appCodeName for both Chrome, Firefox, IE, Safari, and Opera
do not rely on product, most browsers returns "Gecko" as product name !!
information from the navigator object can often be misleading, and should not be used to detect browser versions because:
different browsers can use the same name
navigator data can be changed by the browser owner
some browsers misidentify themselves to bypass site tests
browsers cannot report new operating systems, released later than the browser
var nt = document.getElementById("navigator_tests");
nt.innerHTML =
"navigator.userAgent: " + navigator.userAgent +
"navigator.appName: " + navigator.appName +
"navigator.appCodeName: " + navigator.appCodeName +
"navigator.appVersion: " + navigator.appVersion +
"navigator.product: " + navigator.product +
"navigator.language: " + navigator.language +
"navigator.languages: " + navigator.languages +
"navigator.platform: " + navigator.platform +
"navigator.cookieEnabled: " + navigator.cookieEnabled +
"navigator.javaEnabled(): " + navigator.javaEnabled() +
"navigator.geolocation: " + navigator.geolocation +
"navigator.onLine: " + navigator.onLine +
"navigator.deviceMemory: " + navigator.deviceMemory +
"navigator.hardwareConcurrency: " + navigator.hardwareConcurrency +
"navigator.serviceWorker: " + navigator.serviceWorker +
"navigator.activeVRDisplays: " + navigator.activeVRDisplays +
"navigator.maxTouchPoints: " + navigator.maxTouchPoints +
"navigator.plugins: " + navigator.plugins +
"navigator.oscpu: " + navigator.oscpu +
"navigator.mimeTypes: " + navigator.mimeTypes +
"navigator.mediaCapabilities: " + navigator.mediaCapabilities +
"navigator.doNotTrack: " + navigator.doNotTrack +
"window.doNotTrack: " + window.doNotTrack;
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection || null;
if (connection) {
nt.innerHTML += "navigator.connection: " + connection +
// Network type that browser uses
"connection.type: " + connection.type +
// Effective bandwidth estimate
"connection.downlink: " + connection.downlink +
// Effective round-trip time estimate
"connection.rtt: " + connection.rtt +
// Upper bound on the downlink speed of the first network hop
"connection.downlinkMax: " + connection.downlinkMax +
// Effective connection type determined using a combination of recently
// observed rtt and downlink values
"connection.effectiveType: " + connection.effectiveType +
// True if the user has requested a reduced data usage mode from the user agent
"connection.saveData: " + connection.saveData;
var type = connection.type;
function updateConnectionStatus() {
nt.innerHTML += "Connection type changed from " + type + " to " + connection.type;
}
connection.addEventListener('change', updateConnectionStatus);
} else {
nt.innerHTML += "navigator.connection NOT supported...";
}
if ('activeVRDisplays' in navigator) {
nt.innerHTML += "activeVRDisplays:"
for(var i = 0; i < navigator.activeVRDisplays.length; i++) {
nt.innerHTML += "Display " + navigator.activeVRDisplays[i].displayId + " is active";
}
} else {
nt.innerHTML += "navigator.activeVRDisplays NOT supported...";
}
nt.innerHTML += "Plugins:";
for(var i = 0; i < navigator.plugins.length; i++) {
nt.innerHTML += navigator.plugins[i].name + " - " +
navigator.plugins[i].filename + " - " +
navigator.plugins[i].description + " - " +
(navigator.plugins[i].version?navigator.plugins[i].version:"");
}
nt.innerHTML += "mimeTypes:"
for(var i = 0; i < navigator.mimeTypes.length; i++) {
nt.innerHTML += "mimeType " + navigator.mimeTypes[i].type;
}
// obtain the usage estimates and present the percentage of storage capacity currently used to the user
nt.innerHTML += "Percentage of storage capacity:";
navigator.storage.estimate().then(function(estimate) {
nt.innerHTML += (estimate.usage / estimate.quota).toFixed(2);
});
geolocation
navigator.geolocation - get the geographical position of a user, available only in secure contexts (HTTPS)
properties
coordinates - position and altitude of the device on Earth
position - position of the concerned device at a given time
position.coords - Coordinates object that defines the current location
position.timestamp - DOMTimeStamp representing the time at which the location was retrieved
positionError - reason of an error occurring when using the geolocating device
positionOptions - object containing option properties to pass as a parameter of Geolocation.getCurrentPosition() and Geolocation.watchPosition()
methods
getCurrentPosition() - current position of the device
watchPosition(success[,error,options]) - used to register a handler function that will be called automatically each time the position of the device changes, returns a watch ID for clearWatch()
clearWatch(id) - unregister location/error monitoring handlers previously installed using Geolocation.watchPosition()
function geoFind() {
var gt = document.getElementById("geolocation_tests");
if (!navigator.geolocation){
gt.innerHTML = "Geolocation is not supported by your browser";
return;
}
function geo_success(position) {
var pos_date = new Date(position.timestamp);
gt.innerHTML =
"Latitude: " + position.coords.latitude + "°" +
"Longitude: " + position.coords.longitude + "°" +
"accuracy: " + position.coords.accuracy +
"altitude: " + position.coords.altitude +
"altitudeAccuracy: " + position.coords.altitudeAccuracy +
"heading: " + position.coords.heading +
"speed: " + position.coords.speed +
"timestamp: " + pos_date.toDateString();
// --- FOR <div id="mapholder"></div> :
// var latlon = new google.maps.LatLng(lat, lon)
// var mapholder = document.getElementById('mapholder')
// mapholder.style.height = '250px';
// mapholder.style.width = '500px';
// var myOptions = {
// center:latlon,zoom:14,
// mapTypeId:google.maps.MapTypeId.ROADMAP,
// mapTypeControl:false,
// navigationControlOptions:{
// style:google.maps.NavigationControlStyle.SMALL
// }
// }
// var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
// var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
// --- JUST IMAGE :
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" +
latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
gt.appendChild(img);
}
function geo_error(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
gt.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
gt.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
gt.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
gt.innerHTML = "An unknown error occurred."
break;
}
}
gt.innerHTML = "Locating";
navigator.geolocation.getCurrentPosition(
geo_success,
geo_error
);
// navigator.geolocation.watchPosition(
// geo_success,
// geo_error,
// {
// enableHighAccuracy: false,
// maximumAge: 3000,
// timeout: 3000
// }
// );
}
Alert/Confirm/Prompt
alert box is often used if you want to make sure information comes through to the user
confirm box is often used if you want the user to verify or accept something
prompt box is often used if you want the user to input a value before entering a page
confirm result... prompt result...
function to_confirm() {
if (confirm("Press a button!")) {
document.getElementById("toc").innerHTML = "You pressed OK!";
} else {
document.getElementById("toc").innerHTML = "You pressed Cancel!";
}
}
function to_prompt() {
var person = prompt("Please enter your name:", "Andrei");
if (person == null || person == "") {
document.getElementById("top").innerHTML = "User cancelled the prompt.";
} else {
document.getElementById("top").innerHTML = "Hello " + person + "! How are you today?";
}
}
Timing
window object allows execution of code at specified time intervals, these time intervals are called timing events
setTimeout(fn, ms) - executes a function, after waiting a specified number of milliseconds
clearTimeout(timeoutVar) - stops the execution of the function specified in setTimeout()
setInterval(fn, ms) - repeats the execution of the function continuously
clearInterval(timeoutVar) - stops the executions of the function specified in the setInterval()
var timeout_clock = document.getElementById('timeout_clock'),
interval_clock = document.getElementById('interval_clock'),
tc,
ic;
var checkTime = (i) => (i<10)?"0"+i:i; // add leading zero
function startTimeoutClock() {
var today = new Date(),
h = today.getHours(),
m = today.getMinutes(),
s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
timeout_clock.innerHTML = h + ":" + m + ":" + s;
tc = setTimeout(startTimeoutClock, 500);
}
function stopTimeoutClock() {
clearTimeout(tc);
timeout_clock.innerHTML = "timeoutClock stopped";
}
startTimeoutClock();
function startIntervalClock() {
ic = setInterval(
() => {d = new Date(); interval_clock.innerHTML = d.toLocaleTimeString()},
1000
);
}
function stopIntervalClock() {
clearInterval(ic);
interval_clock.innerHTML = "intervalClock stopped";
}
startIntervalClock();
cookie
document.cookie property - let you store user information in web pages
invented to solve the problem "how to remember information about the user"
when a browser requests a web page from a server, cookies belonging to the page is added to the request
none of the examples below will work if your browser has local cookies support turned off
document.cookie will return all cookies in one string much like: "cookie1=value;cookie2=value; cookie3=value;"
var ctr = document.getElementById("cookie_tests_result");
var cookie_key = document.getElementById("cookie_key");
var cookie_value = document.getElementById("cookie_value");
function cookieGet () {
ctr.innerHTML += docCookies.getItem(cookie_key.value);
}
function cookieSet () {
if (docCookies.setItem(cookie_key.value,cookie_value.value)) {
ctr.innerHTML += "Ok, "+cookie_key.value+"="+cookie_value.value+" is set";
} else {
ctr.innerHTML += "Problem :(";
}
}
function cookieDel () {
if (docCookies.removeItem(cookie_key.value)) {
ctr.innerHTML += "Ok, "+cookie_key.value+" removed";
} else {
ctr.innerHTML += "Problem :(";
}
}
function cookieExists () {
if (docCookies.hasItem(cookie_key.value)) {
ctr.innerHTML += "Ok, "+cookie_key.value+" exists";
} else {
ctr.innerHTML += "No such cookie :(";
}
}
function cookieKeys () {
console.log(document.cookie)
ctr.innerHTML += "*** cookies ***";
docCookies.keys().map((k)=>{
ctr.innerHTML += k;
})
ctr.innerHTML += "***************";
}
// cookies reader/writer framework with full unicode support:
// docCookies.getItem(key)
// docCookies.setItem(key,val[,exp_seconds,path,domain,secure])
// docCookies.removeItem(key)
// docCookies.hasItem(key)
// docCookies.keys(key[,path,domain])
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(
document.cookie.replace(
new RegExp("(?:(?:^|.*;)\\s*" +
encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") +
"\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1"
)
) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
// vEnd - max-age in seconds (31536e3 for a year, Infinity for a never-expire)
// or expires date in GMTString format or as Date object
// if not, the specified the cookie will expire at the end of the session
// sPath - must be absolute
// from where the cookie will be readable. E.g., "/", "/mydir"
// defaults to the current path of the current document location
// sDomain -from where the cookie will be readable
// "example.com", ".example.com" (all subdomains) or "subdomain.example.com"
// defaults to the host portion of the current document location
// bSecure -
// cookie will be transmitted only over secure protocol as https
if (
!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)
) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ?
"; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" +
encodeURIComponent(sValue) +
sExpires +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "") +
(bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) +
"=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
(sDomain ? "; domain=" + sDomain : "") +
(sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (
!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)
) { return false; }
return (
new RegExp("(?:^|;\\s*)" +
encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") +
"\\s*\\=")
).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(
/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, ""
).split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) {
aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
}
return aKeys;
},
// create a GMTString from a relative time
maxAgeToGMT: function (nMaxAge) {
return nMaxAge === Infinity ? "Fri, 31 Dec 9999 23:59:59 GMT" :
(new Date(nMaxAge * 1e3 + Date.now())).toUTCString();
}
};