Workspace
  • Study Book
  • WEB Network HTTP etc
    • Performance Optimization
    • Performance Optimization
    • HTTP/2 & SPDY
    • WebSocket
    • HTTP Header
    • Cross-Origin Resource Sharing
    • JSON, XML, other format
  • Javascript
    • Promise
    • make API call
    • Web API
    • Common JS
    • AJAX
    • Event DOM and delegation
    • ES6 new features
    • special function
    • function API
  • React
    • class component
    • Example
    • Lifting functions/ state up
    • Hot Loader
    • Testing
    • New Features
    • Hook
    • Simple code
    • Life Cycle
  • CSS
    • Horizontal & Vertical Align
    • GPU Animation
    • transform-function
    • LVHA Pseudo-classes
    • Selector
    • How To CSS
  • HTML
  • Redux
  • NodeJS
    • File System
  • express
    • express questions
    • express mongodb
  • Restful API
  • MongoDB
  • Compare
  • Test
    • Jest
  • Deploy development
  • coding question
  • DevOps
  • Webpack
  • GraphQL
Powered by GitBook
On this page
  • Web History API
  • The History back() Method
  • The History go() Method
  • history API vs history hash
  • Web Storage API
  • The localStorage Object
  • The setItem() Method
  • The getItem() Method
  • The sessionStorage Object
  • The setItem() Method
  • The getItem() Method
  • Storage Object Properties and Methods
  • Related Pages for Web Storage API
  • Web Geolocation API
  • Displaying the Result in a Map
  • Location-specific Information
  • DOM API
  • Document:

Was this helpful?

  1. Javascript

Web API

A Web API is a developer's dream.

  • It can extend the functionality of the browser

  • It can greatly simplify complex functions

  • It can provide easy syntax to complex code

Browser APIs

All browsers have a set of built-in Web APIs to support complex operations, and to help accessing data.

For example, the Geolocation API can return the coordinates of where the browser is located.

Example

Get the latitude and longitude of the user's position

var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}

Web History API

The History back() Method

The back() method loads the previous URL in the windows.history list.

It is the same as clicking the "back arrow" in your browser.

<button onclick="myFunction()">Go Back</button>
<script>
function myFunction() {
  window.history.back();
}
</script>

The History go() Method

The go() method loads a specific URL from the history list:

<button onclick="myFunction()">Go Back 2 Pages</button>

<script>
function myFunction() {
  window.history.go(-2);
}
</script>

Loads the previous URL in the history list

Loads the next URL in the history list

Loads a specific URL from the history list

history API vs history hash

before history api, use

window.location.hash = 'qq'

var hash = window.location.hash // '#qq'

window.addEventListener('hashchange', function(){ })

window.onhashchange = function(event){ console.log(event.oldURL, event.newURL); let hash = location.hash.slice(1); document.body.style.color = hash; }

2 problem, first hash not work. second, only url.

window.history.pushState(state, title, url)

window.history.replaceState(state, title, url)

window.addEventListener("popstate", function() { });

window.history.back()

window.history.go(1)

(1)url: hash have # ; history

(2)reload: hash works; history 404

(3)historyHTML5 API

Why we need router?

Single page app, page changes

change new DOM using pathname.

https://juejin.cn/post/6935044153248071716

Web Storage API

The Web Storage API is a simple syntax for storing and retrieving data in the browser. It is very easy to use:

localStorage.setItem("name", "John Doe");

localStorage.getItem("name");

The localStorage Object

The localStorage object provides access to a local storage for a particular Web Site. It allows you to store, read, add, modify, and delete data items for that domain.

The data is stored with no expiration date, and will not be deleted when the browser is closed.

The data will be available for days, weeks, and years.

The setItem() Method

The localStorage.setItem() method stores a data item in a storage.

It takes a name and a value as parameters:

Example

localStorage.setItem("name", "John Doe");

The getItem() Method

The localStorage.getItem() method retrieves a data item from the storage.

It takes a name as parameter:

Example

localStorage.getItem("name");

The sessionStorage Object

The sessionStorage object is identical to the localStorage object.

The difference is that the sessionStorage object stores data for one session.

The data is deleted when the browser is closed.

Example

sessionStorage.getItem("name");

The setItem() Method

The sessionStorage.setItem() method stores a data item in a storage.

It takes a name and a value as parameters:

Example

sessionStorage.setItem("name", "John Doe");

The getItem() Method

The sessionStorage.getItem() method retrieves a data item from the storage.

It takes a name as parameter:

Example

sessionStorage.getItem("name");

Storage Object Properties and Methods

Property/Method

Description

Returns the name of the nth key in the storage

Returns the number of data items stored in the Storage object

Returns the value of the specified key name

Adds that key to the storage, or update that key's value if it already exists

Removes that key from the storage

Empty all key out of the storage

Related Pages for Web Storage API

Property

Description

Allows to save key/value pairs in a web browser. Stores the data with no expiration date

Allows to save key/value pairs in a web browser. Stores the data for one session

Web Geolocation API

The getCurrentPosition() method is used to return the user's position.

The example below returns the latitude and longitude of the user's position:

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>

Displaying the Result in a Map

To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

Example

function showPosition(position) {
  var latlon = position.coords.latitude + "," + position.coords.longitude;

  var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
  "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

  document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}

Location-specific Information

This page has demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

  • Up-to-date local information

  • Showing Points-of-interest near the user

  • Turn-by-turn navigation (GPS)

DOM API

Document:

document.body

represents the <body> or <frameset> node of the current document, or null if no such element exists.

alert(document.body.id); // "oldBodyElement"

var aNewBodyElement = document.createElement("body");

aNewBodyElement.id = "newBodyElement";
document.body = aNewBodyElement;
alert(document.body.id); // "newBodyElement"

Document.font

returns the FontFaceSet interface of the document.

document.fonts.ready.then(function() {
  // Any operation that needs to be done only after all the fonts
  // have finished loading can go here.
});

Document.domain

domain property of the Document interface gets/sets the domain portion of the origin of the current document, as used by the same-origin policy.

Document.event

Event.cancelBubbleA historical alias to Event.stopPropagation(). Setting its value to true before returning from an event handler prevents propagation of the event.

Event.composedPath()

Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its ShadowRoot.mode closed.

Event.preventDefault()

Cancels the event (if it is cancelable).

Event.stopImmediatePropagation()

For this particular event, prevent all other listeners from being called. This includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance).

Event.stopPropagation()

Stops the propagation of events further along in the DOM.

Previousmake API callNextCommon JS

Last updated 2 years ago

Was this helpful?

back()
forward()
go()
key(n)
length
getItem(keyname)
setItem(keyname, value)
removeItem(keyname)
clear()
window.localStorage
window.sessionStorage