Unit 4: HTML APIs
Which three types of information are provided by a successful Geolocation request? Choose three answers.
- Altitude - Longitude - Latitude
Which three actions are made possible by the HTML5 File API? Choose 3 answers.
- Limiting the types of files that can be selected for upload - Reading the contents of a file selected by a user - Discovering metadata about a file selected by a user __________________________________________ The File API provides file metadata such as name, type, and size. The File API includes a FileReader which can be used to read the raw data of a selected file. The File API supports the "accept" attribute on a file input, where allowed file type extensions can be specified.
fetch( ) function definition
- The fetch( ) method starts the process of fetching a resource from a server. - The fetch( ) method returns a Promise that resolves to a Response object.
To edit existing elements other usual methods are:
- html(HTML code) replaces the current content of the element by the HTML code (formatted text); - text(string) replaces the current content of the element by the unformatted text string; - val(string) sets the value of the text property of the element (usually an <input> element) with the unformatted string; - attr(attribute,value) that sets an attribute and its value for the element; - empty( ) removes all contents of the element without removing it; - remove( ) removes the whole element (including child elements).
Finally, jQuery also offers methods to associate event handlers to be activated when certain actions occur:
- ready(function) the DOM is fully loaded; - select(function) an element is selected; - resize(function) the window is resized; -submit(function) the submit event is triggered (likely a submit button element is clicked).
Common HTML5 APIs
1) Geolocation API allows a website to identify a visitor's location. 2) Pointer Events API allows the website to know when a visitor has moved their mouse pointer or interacted with an object on the page. These APIs are usually accessed via a website's JavaScript code, although some can be used with HTML alone. 3) Canvas API can be used to draw graphics outside of the standard HTML document flow, allowing a web app to draw specific content based on the user's interactions. 4) Drag and Drop API can be applied to allow users to organize files or lay out visual elements. 5) History API can control the web browser URL, allowing the application to represent navigational changes in the app without reloading the page. Controlling URL history in this way means that specific application states can be bookmarked by the user, even if those states do not have their own HTML pages. 6) File System API can enable access to a user's local file system so that they can open or save files in a web app.
Some of the more relevant canvas methods for drawing paths are:
1) beginPath( ) begins a path, or resets the current path; 2) lineTo(x,y) moves the current path position to the coordinate x,y creating a line; 3) moveTo(x,y) moves the current path position to the coordinate x,y without creating a line; 4) arc(x,y,r,sa,ea,d) draws an arc (a segment of a circle) indicated by the center of the circle (x,y), its radius (r), and starting and ending angles (sa, ea), plus an optional direction (True for counterclockwise or False for clockwise - the default value); 5) closePath( ) moves the current path position back to the first point creating a line to the first path coordinate; 6) fill( ) fills the current path, i.e., it fills a polygon; 7) stroke( ) draws the current path.
generic methods that can be used for both rectangles and paths:
1) fillStyle( ) lets or returns the color, gradient, or pattern used to fill the current object (a path, a rectangle, etc.); 2) lineWidth() sets the width of the current object (a path, a rectangle, etc.);
Some of the recommended drag data formats are:
1) text/plain for text 2) text/uri-list for links 3) text/html for HTML code
Which code must be present on a web page for a website to make use of the AppCache API?
<html manifest="my-website.appcache"> ___________________________________________________ The opening html tag must use the manifest attribute to reference the site's appcache file.
File API's FileReader
The File API's FileReader is one of the oldest and most stable of these APIs and is widely used across the web. The FileReader allows a user to give access to a file on their system so that the web page can process the contents of that file, but it does not give the browser permission to modify or delete the actual file on the user's system.
Geolocation API
The Geolocation API is accessed in JavaScript via the browser's navigator API, under navigator.geolocation. The Geolocation API offers a getCurrentPosition function which accepts three parameters: a success handler function, an error handler function, and an options object. If the geolocation request is successful, then the success handler will be passed a GeolocationPosition object containing a timestamp and any available location information. This function must be called once each time the user's location is required.
Reverse Geocoding
The Geolocation API provides a user's location as latitude and longitude coordinates, and is often used alongside a secondary service like Google Maps JavaScript API, which can display the location on a map, or Reverse Geocoding, which can transform those coordinates into the name of a country or city.
The Document Object Model (DOM)
is a programming API [Application Programming Interface] for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. - The browser's goal is to do its best to turn the HTML into a valid DOM that can be rendered in the way the writer intended. (image) -The DOM can be visualized as a tree of objects, related to each other with connections, referred to as nodes.
Drag and drop functionality
is most frequently used for uploading files, as shown, but can also be used for more complex apps like drag and drop website builders or image editing tools.
Other useful jQuery methods that can be employed to add new elements are:
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, ... - append(element) inserts the parameter element inside the element at the last index; - prepend(element) inserts the parameter element inside the element at the first index; - before(element) inserts the parameter element before the element; - after(element) inserts the parameter element after the element;
Using jQuery
jQuery makes heavy use of CSS selectors for finding elements on a page, so many of the CSS selectors familiar to web developers can be cross applied to using jQuery. One of the important characteristics of jQuery calls is that they have to be preceded by a dollar sign ($) and placed between parenthesis of the jQuery request. Some common examples follow: - Getting a specific object by its id: - Getting an array of many objects by their class name: - Finding a specific object by element CSS selector: - Update the innerHTML of a jQuery element: - Inserting content at the beginning of an element by the element type: - Create a new element and add it to the DOM after an existing element:
Given the following code snippet: 1. var request = new XMLHttpRequest(); 2. request.addEventListener('load', onRequestSuccess); 3. request.addEventListener('error', onRequestError); 4. 5. request.send(); Which code should be inserted on line 4 to complete the request?
request.open('GET', 'https://my-api.com/data');
Which code is used to retrieve the two dimensional drawing context of a canvas element?
var ctx = canvas.getContext('2d');
How can a custom entry be added to the browser's navigation history?
history.pushState({page: 1}, 'Page One', '?page=1')
<canvas> element syntax
A canvas element can be created from either HTML or from JavaScript, but the most common approach is to use the <canvas> HTML element. When creating a canvas using HTML, there are three attributes which are almost always used; "width" and "height" are used to determine the size of the canvas in pixels, while an "id" should be specified so that it can be used to access the canvas element from JavaScript. The canvas element also requires that both opening and closing HTML tags are included. <canvas id="my-canvas" width="300" height="200"></canvas>
What is the Document Object Model (DOM)?
A logical structure for accessing and manipulating HTML or XML documents
fetch( ) function
A more modern alternative is the Fetch API which is based on a promise rather than callbacks. With this approach, the global fetch() function is called with a specific URL and the promise's chained then and error functions handle the result or error of the request.
What is a programming API?
A set of well-defined functions which can be used to interact with a system
Service Worker API
A significant portion of content on the web is now delivered by CDNs, so compatibility with them is critical to support the needs of the modern web. Service workers are a relatively new concept, and their use cases are much wider than just offline caching. Service workers are standalone scripts written in JavaScript that are loaded alongside normal websites but can run in a privileged environment in the browser that allows them to run background tasks. This separation from the website allows service workers to achieve use cases such as triggering push notifications or polling for new data while the user browses another website. Implementing an AppCache alternative with a service worker requires that the desired files be explicitly added to the cache when the website is loaded. Future network requests must also be intercepted to check the cache for a matching file before continuing with the usual process of requesting that file from the server.
DOM tree and javascript
According to the Document Object Model (DOM), every HTML tag is an object. Nested tags are "children" of the enclosing one. The text inside a tag is an object as well. All these objects are accessible using JavaScript, and we can use them to modify the page. _____________________________________________ For example, document.body is the object representing the <body> tag. Running this code will make the <body> red for 3 seconds: documemennt.body.style.background = 'red'; // make the background red setTimeout(( ) => documement.body.style.background = '', 3000); // return back _____________________________________________ Here we used style.background to change the background color of document.body, but there are many other properties, such as: - innerHTML - HTML contents of the node. - offsetWidth - the node width (in pixels) Soon we'll learn more ways to manipulate the DOM, but first we need to know about its structure.
Given the following code snippet: <li>Drag Me</li> How can the element be modified to enable dragging?
Add the attribute draggable="true"
Another example of an XMLHttpRequest
Another example of an XMLHttpRequest is the following in which just a portion of the page is updated without reloading the whole page. In this example, the XMLHttpRequest object is defined in the first line. The second line specifies the onreadystatechange property that is executed every time the status of the object changes. Inside that function, the if command tests the readyState and the status properties that must indicate that the response is ready (respectively 4 and 200 values). The responseText property returns the server response as a text string. Finally, the methods open and send, respectively, perform the required operation (in this example, a "GET" operation, a text file to be displayed, a boolean value, with true indicating asynchronous mode and false indicating synchronous mode).
File System Access API
An option for modifying or creating new files, which is a very recent specification, is the File System Access API. This API is not yet implemented in all browsers, but its purpose is to enable a web app to read and write files in the computer's local file system in much the same way as a native app. It supports: - opening directories - opening files - saving files __________________________________________ This API can access private data, and therefore is restricted to use only on websites hosted with https and requires explicit user permission before accessing files. File system interactions from a web app can be very useful when a user needs to upload or edit a file as part of the interaction with the app. Using this API, an app could be designed where a user could upload an image file, edit that file directly in the browser, and then save it back to their computer without ever sending that image to a server. The same could be achieved for video files or text documents, where there could be value in reducing the need to upload large files to a server before editing.
jQuery to load
Another common solution is to use jQuery to load data. jQuery's AJAX syntax is quite easy to read and many sites already use jQuery for other functionality, making it an easy choice in those cases. Including jQuery in a website requires adding a script tag in the head of the document to import the jQuery library. jQuery is also useful for dynamically updating the page, because it offers some simple APIs for querying the DOM, adding event listeners, and updating the DOM. These DOM capabilities work well alongside AJAX, because they provide an easy way to transform the loaded data into HTML and apply it to the existing DOM of the page without a page refresh. The recommended way to include jQuery on a page is to include the CDN script tag, which is a link to the jQuery JavaScript file hosted on an official server. Including jQuery in this way means that there is no need to download or copy the full jQuery library into your actual project code.
metadata
Are all objects in the DOM visible to web page users? No. Some objects in the DOM are visible on the web page, such as an image or a paragraph of text. Other objects are not visible, such as page metadata, which is present in the HTML code and in the DOM, but not visible to the person visiting the web page.
Browser plug-ins
Browser plug-ins filled this gap, allowing developers and web users to opt-in to this advanced functionality. Adobe Flash was one well-known plugin of this kind, supporting video playback and highly interactive content, such as animations and games. Over time, web browsers have added native support for the many of the common use cases where a plug-in was required in the past. __________________________________________________________________ An add-on for a program that adds functionality to it, i.e., a Photoshop plug-in may add extra filters that you can use to manipulate images, or a browser plug-in like Macromedia Flash or Apple QuickTime allows you to play certain multimedia files within your Web browser.
DOM APIs (Application Programming Interfaces)
DOM is an application program interface that defines the structure of HTML and XML documents, as was described in the tree model. Because the DOM API provides an interface for interacting with page elements, it is often used by software which needs to access information about the page in an automated way. The DOM is accessed by search indexing bots like Google or Bing. These bots generate search results—a bot can get more detailed information about the page by looking at the underlying DOM than it can from just the visual elements of the page. The DOM is also seen and interpreted by assistive software, such as screen readers for individuals with vision impairment.
devices and location accuracy
Different devices will give different levels of accuracy, so this is also important to consider. The results are not always accurate because different devices have different location capabilities.
Which browser API requests a user's permission to open a file directly without uploading it?
File system access
Canvas API
Modern web browsers support a wide range of Web APIs that allow web developers to add advanced functionality to a web page. One such API is the Canvas API, which can be used to draw graphics on the page using JavaScript. Drawing graphics using code enables a developer to create dynamic visual content which can react to changes in some underlying data, or in response to user interaction. Canvas can even be used to create animations, where the drawing code runs on a timer and changes over time.
draggable attribute and dragstart event handler.
For an element to be draggable, it must have the attribute draggable set to true in the HTML. Images, links, and portions of selected text on a web page are draggable by default but adding drag support to any other element requires this attribute.
watchPosition function
For cases where the user's location needs to be tracked over time, another function called watchPosition is available. This function accepts the same parameters as getCurrentPosition but will continue to watch the user's location and will call the success function each time a new location update is available. The position watcher can be stopped using the clearWatch function.
AppCache API
For many years, the best solution to offline website caching has been the AppCache API. The AppCache API is still supported in some browsers, but has officially been deprecated in favor of the Cache API which is a subset of the Service Worker API.
why we need the pushState function
For most multi-page websites, the browser's built-in history tracking is enough, since it records each page that is visited. However, for web applications it is common to load data in the background and update the page visually without reloading it. Because the page's URL never changes, the history is never updated and there is no way for the user to navigate back or forward. In this SPA case, the web app developer must implement support for browser history using the History API. The History API allows for manually adding history entries using the pushState function. This function accepts three parameters, which have varying levels of support across browsers. Pushing new state to the browser history is only the first half of implementing hand-crafted history, because the page also needs a way to read those states and re-apply them to the page when the user navigates back or forward. The History API offers an event called popstate for this purpose, which is emitted by the window. This event occurs whenever the current point in the linear history is changed due to the user navigating.
Which browser API is used when an online shopping site suggests a user's nearest physical store?
Geolocation
Javascript and DOM
JavaScript allows for advanced web page functionality. JavaScript is an interpreted coding language, meaning that the JavaScript code executes directly within the client web browser. Incorporating JavaScript into the web page allows for a more dynamic and interactive web page experience. - JavaScript code is interpreted and the interpreter is the web browser. The language is sometimes referred to as a scripting language. - Client-side JavaScript combines the ability of the interpreter inside the browser with the Document Object Model (DOM), defined by that same browser.
drop target
Making an element draggable ensures it can be used with existing drop areas. For example, any image can be dragged into another browser window to open the image URL directly. Any text or link can be dragged into a text area. In addition to these existing drop-compatible targets, it is possible to make an element of a web page into a drop target using event handlers. Creating a drop target requires event handlers for both the dragover and the drop events. The dragover event must be handled to prevent the default behavior of blocking a drop action on the element. The drop event must be handled to process the dropped element data however is required for the application's drag and drop use case.
AJAX
On the modern web, it is common to see examples of websites where the page is updated without requiring a refresh. Some examples of this are when a social media feed automatically updates, or the load more button on a shopping site loads more results below the existing ones. This development pattern requires that data be loaded asynchronously and is achieved by using JavaScript to request new data in the background. When the data has been loaded successfully, JavaScript is also used to update the DOM, by adding or removing page elements as needed, to reflect the new data. This pattern is commonly referred to as AJAX, which stands for Asynchronous JavaScript and XML, and refers to a broad overarching concept rather than one exclusive technology.
Opening a text file in JavaScript
Opening a text file in JavaScript requires that the file is selected, the FileSystemFileHandle reference is saved, the file data is extracted, and then that raw data is processed. File objects in JavaScript are comparable to the Blob data type, which is a raw data format.
popstate
Pushing new state to the browser history is only the first half of implementing hand-crafted history, because the page also needs a way to read those states and re-apply them to the page when the user navigates back or forward. The History API offers an event called popstate for this purpose, which is emitted by the window. This event occurs whenever the current point in the linear history is changed due to the user navigating. ____________________________________________________ window.addEventListener('popstate', function(event) { console.log('new state:', event.state); console.log('new url:', location.href); console.log('new path:', location.pathname); }); This detailed management of browser history allows for complex applications with support for linking to specific internal pages or states within a single-page web app.
relevant canvas methods for drawing rectangles
Some of the more relevant canvas methods for drawing rectangles (upper-left corner x,y size w,h) are: - strokeRect(x,y,w,h) draws an unfilled rectangle (just the frame); - fillRect(x,y,w,h) draws a filled rectangle (color pixels within); - clearRect(x,y,w,h "unfills" the rectangle (clear pixels).
DOM API and Javascript
The DOM API also includes a JavaScript API which can be used for manipulating the DOM structure. Elements in the DOM can be retrieved by ID, by class, or by a CSS selector. These elements can be created, added to the DOM, or removed from the DOM. Their properties and attributes can also be modified. This allows a developer to update the page structure in reaction to user interactions. An example would be adding an item to a list dynamically, or removing an item that the user has marked as deleted. Using JavaScript to make these DOM changes means that the feedback is immediate, and the page does not need to be reloaded to see the new state.
DOM API
The DOM API has many methods available for manipulating the DOM from JavaScript.
Nodes and tree model
The DOM can be visualized as a tree of objects, related to each other with connections, referred to as nodes. Every node of the tree is the document itself, referred to as the root node. The segments that are closest to the root are referred to as parent nodes. Segments attached to the parent nodes are referred to as child nodes. In this tree representation, HTML elements can be nested within each other, so the DOM represents this as a parent-child relationship between nodes, where the parent is the node which is closer to the document root. Every node in the DOM has a parent except for the document root. A parent node can have no children, one child, or many children.
history.pushState(state, title, url)
The History API allows for manually adding history entries using the pushState function. This function accepts three parameters, which have varying levels of support across browsers: history.pushState(state, title, url) stateAny JavaScript object of interest to the developer that they want to store alongside the history entry. Should be null if not needed. titleA plain text title for the history entry, currently ignored by most browsers. Should be an empty string '' if not needed. urlThe URL of the history entry, which is applied to the URL bar. This URL can be bookmarked by the user and will be requested from the server if the page is reloaded. Should be left out if not needed.
getCurrentPosition function Example
The basic usage of the getCurrentPosition function is exemplified by the following code, where the the navigator.geolocation API is called and the result is saved in a variable called result, that can be assigned local variables with both latitude and longitude positions, respectively lat and lon. navigator.geolocation.getCurrentPosition(function(result) { var lon = result.coords.longitude; var lat = result.coords.latitude; });
canvas element and rendering contexts
The canvas element supports a few different rendering contexts. The most useful are the '2d' context for flat two-dimensional drawing, and webgl or webgl2 for three-dimensional rendering. The canvas element provides the getContext JavaScript method, which is used to request the preferred rendering context. Drawing commands are executed on the context rather than directly on the canvas itself. For 2D rendering we use canvas.getContext('2d') which returns a CanvasRenderingContext2D JavaScript object. This 2D context offers a specific set of functions which support drawing in 2D. A canvas without any drawing commands just looks like an empty white rectangle. Drawing commands in the 2D context are described using a coordinate system where [0, 0] is at the top left of the canvas.
Using file API's FileReader
The most basic way to use the File API is by adding an input element to the page with its type set to "file". <!-- The `multiple` attribute lets users select multiple files. --> <input type="file" id="file-selector" multiple> This input element is then referenced from the JavaScript to add the necessary event handlers to capture the file selection when it occurs. See an example of this as shown: (see image)
Historical Events in Navigation
The user agent fires a popstate event when the user navigates through their history, whether backwards or forwards, provided it isn't taking the user away from the current page. That is, all those pushStates we called will keep the user on the current page, so the popstate event will fire for each history item they pop through. Before the closing script tag, add a new listener for the popstate event: // Revert to a previously saved statewindow.addEventListener('popstate', function(event) {console.log('popstate fired!');updateContent(event.state);}); We attach the event listener to the window, which is responsible for firing the event, and pass this event into our handler. We log a message (so we can see when this event is firing), and then we update the content using the state we saved previously. The state is attached to the event object via the state property. Open up the page fresh in your browser, click around like before, and then click back. As before, the URL in the address bar changes as you cycle through states, but now the content is also restored back to what it should be. Click forward, and the content is likewise correctly restored.
3 file system methods
There are three file system methods available, all of which are accessed via the global window object in JavaScript. 1) showDirectoryPicker method shows a native directory selection window where the user can select a directory to open. 2) showFilePicker method shows a similar window, allowing the user to select one or more files. 3) showSaveFilePicker method allows the user to choose where to save a file.
using CanvasRenderingContext2D
To get a CanvasRenderingContext2D instance, you must first have an HTML <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> To get the canvas' 2D rendering context, call getContext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getElementById("my-house"); const ctx = canvas.getContext("2d"); _______________________________________________ With the context in hand, you can draw anything you like. This code draws a house: // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); The resulting drawing looks like this: (see image)
Data format and data loading libraries
Ways to Load data asynchronously 1) XMLHttpRequest 2) Fetch API 3) jQuery library That said, it is more common now for the data format to be JavaScript Object Notation (JSON) rather than XML. JSON is more human-readable and lightweight in file size. For these reasons, JSON tends to be preferred over XML by many developers and has become the data format of choice for most modern web-based systems. There are several browser technologies and JavaScript libraries available for loading data asynchronously. Purely browser-based APIs include XMLHttpRequest and the Fetch API. These are available in all modern browsers. It is still common to see the jQuery library used because it simplifies the code required to make a request. Ways to Load data in asynchrony 1) XMLHttpRequest 2) Fetch API 3) jQuery library
Nodes and DOM traversing
We will use document methods to walk through or traverse our document and change it. You need to think of the document as a tree with nodes. What is attached to these nodes are your HTML tags with their attributes and inner HTML text. With dedicated methods, we can look for parts of our document. A node or node list is what they return (sometimes there is only one matching tag, sometimes there are more). Then, by changing the properties of these nodes or using other methods, we can effectively change the content or layout of our document. _____________________________________________ Three useful methods for looking up things in the document tree are: getElementById: find the node with the id specified as argument getElementsByClassName: get the node(s) with the class set to argument getElementsByTagName: get all node(s) where the HTML tag equals argument
History API
Web browsers track a user's browsing history by default because it offers a positive user experience. This linear historical record of the pages that have been visited is the same history that can be manipulated by the History API. On a normal multi-page website, the History API can be used for adding visual back and forward buttons to the page, in addition to the default browser buttons. This is most commonly seen on websites where the user may wish to navigate through pages of documentation or a series of steps in a tutorial. This is not common on websites, because it simply duplicates the existing functionality of the browser buttons. The History API's back and forward functions can be used from JavaScript. ________________________________________________ history.back( ) // go back to the previous page history.forward( ) // go forward to the next most recent page
caching
When a device does not have an internet connection for some reason, the website will not load at all and will display an error. Using some modern browser APIs, the browser can be instructed to cache particular files, saving them directly on the device for later access. When on-device caching is used appropriately, a website that has been loaded at least once previously with an active internet connection can be loaded successfully again later when a connection is no longer available.
Document Object Model (DOM)
When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is constructed as a tree of Objects. The HTML DOM is a standard object model and programming interface for HTML. It defines: - The HTML elements as objects - The properties of all HTML elements - The methods to access all HTML elements - The events for all HTML elements In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements. ________________________________________________ - The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. The Document Object Model (DOM) is an application programming interface (API) that defines a way to access and manipulate documents, as well as their logical structure. A DOM can be considered a container of data that is in a variety of formats. It can be a file in a specific structure, such as an XML or HTML file. However, while a DOM could be defined as almost any format, in the W3C context the DOM for XML and HTML formats is commonly referred to simply as the DOM. Programmers can use the DOM API to create, edit and add content to XML and HTML documents. The main goal of the DOM is to provide a standard programming interface to be used to access documents over the Internet, and for that reason, DOM was specified by the W3C.
dragstart event handler.
When any element is dragged, the information describing that element must be attached to the drag event using the DataTransfer interface. For images, links, and text selections this data is set automatically by the browser, but for all other elements it must be set by the developer inside the dragstart event handler.
XMLHttpRequest
XMLHttpRequest is the native option that has been around for the longest. This method of loading data requires creating an XMLHttpRequest object in the JavaScript, which can then be used to request data from a specific URL. The XMLHttpRequest object then emits events when the request is successful or has an error. ______________________________________________________________ The outcome of the XMLHttpRequest object is informed by the readyState and the status properties. The values for such properties and corresponding meaning are: (see image)
Application Programming Interfaces (APIs)
You have learned that an API provides a set of available actions (an interface) that can be used by programmers to perform interactions with an application. APIs are usually well-documented and structured in a predictable way so that it is easy for a programmer to understand which actions might be available and how to use them. APIs often specify how a programmer could send data to an application, retrieve data, or trigger an action from their code. Think about a software application or web platform that you are familiar with. The API of that platform is most easily understood by thinking of the actions commonly taken by users of that platform and understanding how a programmer might want to perform those actions on behalf of the user. __________________________________________________ Twitter is a platform for posting short messages, either publicly or privately, as well as subscribing to messages posted by others. The Twitter API therefore defines how a programmer could use a programming language of their choice to send a tweet, delete a tweet, follow an account, send a private message, or perform any number of other actions that a program may want to take on behalf of a user. Web browsers support a wide range of APIs which can be used by website developers. For example, a browser's Geolocation API allows a website to request information about a visitor's location, delivering the IP address of the client device. Another example is the Pointer Events API that allows the website to know when a visitor has moved their mouse pointer or interacted with an object on the page. These APIs will be further discussed in an upcoming section. Browser APIs are usually accessed via a website's JavaScript code, although some can be used with HTML alone.
Web APIs
You have learned that web browsers represent all the elements of a web page in a logical structure called the Document Object Model (DOM). This structure can be accessed and manipulated using JavaScript, thanks to the programming functions provided by the DOM API. This API enables web pages to add, remove, or modify elements on the page, either automatically or when a user interacts. Web browsers such as Chrome, Firefox, Edge, and others, support a wide range of Web APIs. These APIs add extra functionality to the browser, which can then be used by website developers. Complex applications can be built by using combinations of these APIs together. Look at the following examples, which also provide links for further exploring each of these APIs.
