Web API 是开发人员的梦想。
它可以扩展浏览器的功能
可以大大简化复杂的功能
它可以为复杂的代码提供简单的语法
API 代表应用程序编程接口。
Web API 是 Web 应用程序编程接口。
浏览器 API 可以扩展 Web 浏览器的功能。
服务器 API 可以扩展 Web 服务器的功能。
所有浏览器都有一组内置的 Web API 支持复杂的操作,并帮助访问数据。
例如,Geolocation API 可以返回浏览器所在位置的坐标。
获取用户位置的纬度和经度:
const myElement = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
myElement.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation</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() {
try {
navigator.geolocation.getCurrentPosition(showPosition);
} catch {
x.innerHTML = err;
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
您的浏览器中未内置第三方 API。
要使用这些 API,您必须从 Web 下载代码。
例子:
YouTube API - 允许您在网站上显示视频。
Twitter API - 允许您在网站上显示推文。
Facebook API - 允许您在网站上显示 Facebook 信息。