JS Web API

 

1. Web  API  简介  (Web  API  Intro)

2. 网络表单 API  (Web  Forms  API)

3. 网络历史  API  (Web  History  API )

4. 网络存储  API  (Web  Storage  API)

5.  网络工作者  API  (Web  Worker  API)

6.网页抓取API  (Web Fetch  API)

7. 网络  地理位置  API (Web Geolocation  API)

 

 

 

 

 

 

 

1. Web  API  简介  (Web  API  Intro)

1. Web API 是开发人员的梦想。

  • 它可以扩展浏览器的功能
  • 可以大大简化复杂的功能
  • 它可以为复杂的代码提供简单的语法

2. 什么是 Web API?

  • API代表应用程序编程接口
  • Web API 是 Web 的应用程序编程接口。
  • 浏览器 API 可以扩展 Web 浏览器的功能。
  • 服务器 API 可以扩展 Web 服务器的功能。

 

3. 第三方 API

第三方 API 未内置在您的浏览器中。

要使用这些 API,您必须从 Web 下载代码。

例子:

  • YouTube API - 允许您在网站上显示视频。
  • Twitter API - 允许您在网站上显示推文。
  • Facebook API - 允许您在网站上显示 Facebook 信息。

 

 

 

 

2. 网络表单 API  (Web  Forms  API)

约束验证 DOM 方法

PropertyDescription
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.

约束验证 DOM 属性

PropertyDescription
validity Contains boolean properties related to the validity of an input element.
validationMessage Contains the message a browser will display when the validity is false.
willValidate Indicates if an input element will be validated.

 

有效性属性

输入元素的有效性属性包含许多与数据有效性相关的属性:

PropertyDescription
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern attribute.
rangeOverflow Set to true, if an element's value is greater than its max attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no value.
valid Set to true, if an element's value is valid.

 

例子:1         

checkValidity() 方法

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  const inpObj = document.getElementById("id1");
  if (!inpObj.checkValidity()) {
    document.getElementById("demo").innerHTML = inpObj.validationMessage;
  } else {
    document.getElementById("demo").innerHTML = "Input OK";
  } 
} 
</script>

</body>
</html>

 

 

例子:  2     

rangeOverflow 属性

如果输入字段中的数字大于 100(输入的max 属性),则显示一条消息:

 
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  let text;
  if (document.getElementById("id1").validity.rangeOverflow) {
    text = "Value too large";
  } else {
    text = "Input OK";
  } 
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

 

 

例子:  3

rangeUnderflow 属性

如果输入字段中的数字小于 100(输入的min属性),则显示一条消息:

 
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Enter a number and click OK:</p>

<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>

<p>If the number is less than 100 (the input's min attribute), an error message will be displayed.</p>

<p id="demo"></p>

<script>
function myFunction() {
  let text;
  if (document.getElementById("id1").validity.rangeUnderflow) {
    text = "Value too small";
  } else {
    text = "Input OK";
  } 
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

 

 

 

3. 网络历史  API  (Web  History  API )

 

Web History API 提供了访问 windows.history 对象的简单方法。

window.history 对象包含用户访问的 URL(网站)

 

历史对象方法

MethodDescription
back() Loads the previous URL in the history list
forward() Loads the next URL in the history list
go() Loads a specific URL from the history list

 

历史对象属性

 

PropertyDescription
length Returns the number of URLs in the history list

例子:

历史 back() 方法

back() 方法加载 windows.history 列表中的前一个 URL。

这与在浏览器中单击“后退箭头”相同。

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

<script>
function myFunction() {
  window.history.back();
}
</script>

 

 

 

4. 网络存储  API  (Web  Storage  API)

 

本地存储对象

localStorage 对象提供对特定网站的本地存储的访问。它允许您存储、读取、添加、修改和删除该域的数据项。

数据存储无有效期,关闭浏览器时不会被删除。

数据将可用于数天、数周和数年

 

 

Web Storage API 是一种用于在浏览器中存储和检索数据的简单语法。这是非常容易使用:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
localStorage.setItem("name","John Doe");
document.getElementById("demo").innerHTML = localStorage.getItem("name");
</script>

</body>
</html>

存储对象属性和方法

Property/MethodDescription
key(n) Returns the name of the nth key in the storage
length Returns the number of data items stored in the Storage object
getItem(keyname) Returns the value of the specified key name
setItem(keynamevalue) Adds that key to the storage, or update that key's value if it already exists
removeItem(keyname) Removes that key from the storage
clear() Empty all key out of the storage

Web Storage API 的相关页面

PropertyDescription
window.localStorage Allows to save key/value pairs in a web browser. Stores the data with no expiration date
window.sessionStorage Allows to save key/value pairs in a web browser. Stores the data for one session

 

 

 

 

 

 

5.  网络工作者  API  (Web  Worker  API)

 

Web Worker 是在后台运行的 JavaScript,不会影响页面的性能。

什么是网络工作者?

在 HTML 页面中执行脚本时,页面会变得无响应,直到脚本完成。

Web Worker 是在后台运行的 JavaScript,独立于其他脚本,不会影响页面的性能。你可以继续做任何你想做的事情:点击、选择东西等等,而 web worker 在后台运行。

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Web Workers API</h2>
<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>

<script>
let w;

function startWorker() {
  if(typeof(w) == "undefined") {
    w = new Worker("demo_workers.js");
  }
  w.onmessage = function(event) {
    document.getElementById("result").innerHTML = event.data;
  };
}

function stopWorker() { 
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Web Workers 和 DOM

由于 Web Worker 位于外部文件中,因此他们无权访问以下 JavaScript 对象:

  • 窗口对象
  • 文档对象
  • 父对象

 

 

 

 

6.网页抓取API  (Web Fetch  API)

Fetch API 接口允许 Web 浏览器向 Web 服务器发出 HTTP 请求。

😀不再需要 XMLHttpRequest。

 

例子1

<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>
<script>

let file = "fetch_info.txt"

fetch (file)
.then(x => x.text())
.then(y => document.getElementById("demo").innerHTML = y);

</script>
</body>
</html>

 

例子2

<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>

<script>
getText("fetch_info.txt");

async function getText(file) {
  let x = await fetch(file);
  let y = await x.text();
  document.getElementById("demo").innerHTML = y;
}
</script>

</body>
</html>

 

例子3

<!DOCTYPE html>
<html>
<body>
<p id="demo">Fetch a file to change this text.</p>

<script>
getText("fetch_info.txt");

async function getText(file) {
  let myObject = await fetch(file);
  let myText = await myObject.text();
  document.getElementById("demo").innerHTML = myText;
}
</script>

</body>
</html>

 

 

 

 

 

7. 网络  地理位置  API (Web Geolocation  API)

 

 

1. 定位用户位置

HTML Geolocation API 用于获取用户的地理位置。

由于这可能会损害隐私,因此除非用户批准,否则该职位不可用。

 

2.使用地理位置 API

getCurrentPosition()方法用于返回用户的位置。

下面的示例返回用户位置的经纬度:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
const 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>

</body>
</html>

示例解释:

  • 检查是否支持地理位置
  • 如果支持,请运行 getCurrentPosition() 方法。如果没有,则向用户显示一条消息
  • 如果getCurrentPosition()方法成功,则返回一个坐标对象给参数中指定的函数(showPosition)
  • showPosition() 函数输出纬度和经度

上面的例子是一个非常基本的地理定位脚本,没有错误处理。

 

 

3.处理错误和拒绝

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
const x = document.getElementById("demo");

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

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

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}
</script>

</body>
</html>

 

4. 在地图中显示结果

要在地图中显示结果,您需要访问地图服务,例如 Google 地图。

在下面的示例中,返回的纬度和经度用于在 Google 地图中显示位置(使用静态图像):

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

  let 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+"'>";
}

 

5. 特定位置信息

此页面演示了如何在地图上显示用户的位置。

地理位置对于特定于位置的信息也非常有用,例如:

  • 最新的本地信息
  • 显示用户附近的兴趣点
  • 逐向导航 (GPS)

 

 

 

6. getCurrentPosition() 方法 - 返回数据

getCurrentPosition()方法在成功时返回一个对象。总是返回纬度、经度和精度属性。如果可用,则返回其他属性:

PropertyReturns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)

 

7. 地理位置对象 - 其他有趣的方法

Geolocation 对象还有其他有趣的方法:

  • watchPosition()- 返回用户的当前位置,并在用户移动时继续返回更新的位置(如汽车中的 GPS)。
  • clearWatch()- 停止该watchPosition()方法。

下面的示例显示了该watchPosition()方法。你需要一个准确的 GPS 设备来测试这个(比如智能手机):

 

 

posted @ 2022-02-23 11:46  漫漫长路</>  阅读(132)  评论(0编辑  收藏  举报