浏览器
元信息(Meta)与链接(Link)
元信息(Meta)
代码
html
<!-- 设置文档的字符编码 -->
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- 以上 3 个 meta 标签 *必须* 放在 head 的最前面;其他任何的 head 内容必须在这些标签的 *后面* -->
<!-- 允许控制资源的过度加载 -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
<!-- 尽早地放置在文档中 -->
<!-- 仅应用于该标签下的内容 -->
<!-- Web 应用的名称(仅当网站被用作为一个应用时才使用)-->
<meta name="application-name" content="应用名称">
<!-- 针对页面的简短描述(限制 150 字符)-->
<!-- 在*某些*情况下,该描述是被用作搜索结果展示片段的一部分 -->
<meta name="description" content="一个页面描述">
<!-- 控制搜索引擎的抓取和索引行为 -->
<meta name="robots" content="index,follow,noodp"><!-- 所有的搜索引擎 -->
<meta name="googlebot" content="index,follow"><!-- 仅对 Google 有效 -->
<!-- 告诉 Google 不显示网站链接的搜索框 -->
<meta name="google" content="nositelinkssearchbox">
<!-- 告诉 Google 不提供此页面的翻译 -->
<meta name="google" content="notranslate">
<!-- 验证 Google 搜索控制台的所有权 -->
<meta name="google-site-verification" content="verification_token">
<!-- 用来命名软件或用于构建网页(如 - WordPress、Dreamweaver)-->
<meta name="generator" content="program">
<!-- 关于你的网站主题的简短描述 -->
<meta name="subject" content="你的网站主题">
<!-- 非常简短(少于 10 个字)的描述。主要用于学术论文。-->
<meta name="abstract" content="">
<!-- 完整的域名或网址 -->
<meta name="url" content="https://example.com/">
<meta name="directory" content="submission">
<!-- 基于网站内容给出一般的年龄分级 -->
<meta name="rating" content="General">
<!-- 允许控制 referrer 信息如何传递 -->
<meta name="referrer" content="no-referrer">
<!-- 允许控制 referrer 信息如何传递 允许获取当前页面的来源 -->
<meta name="referrer" content="always">
<!-- 禁用自动检测和格式化可能的电话号码 -->
<meta name="format-detection" content="telephone=no">
<!-- 通过设置为 “off” 完全退出 DNS 预取 -->
<meta http-equiv="x-dns-prefetch-control" content="off">
<!-- 在客户端存储 cookie,web 浏览器的客户端识别 -->
<meta http-equiv="set-cookie" content="name=value; expires=date; path=url">
<!-- 指定要显示在一个特定框架中的页面 -->
<meta http-equiv="Window-Target" content="_value">
<!-- 地理标签 -->
<meta name="ICBM" content="latitude, longitude">
<meta name="geo.position" content="latitude;longitude">
<meta name="geo.region" content="country[-state]"><!-- 国家代码 (ISO 3166-1): 强制性, 州代码 (ISO 3166-2): 可选; 如 content="US" / content="US-NY" -->
<meta name="geo.placename" content="city/town"><!-- 如 content="New York City" -->链接(Link)
代码
html
<!-- 有助于防止出现内容重复的问题 -->
<link rel="canonical" href="https://example.com/2010/06/9-things-to-do-before-entering-social-media.html">
<!-- 之前用于包含 icon 链接,但已被废弃并不再使用 -->
<link rel="shortlink" href="https://example.com/?p=42">
<!-- 链接到当前文档的一个 AMP HTML 版本 -->
<link rel="amphtml" href="https://example.com/path/to/amp-version.html">
<!-- 表明一个 CSS 样式表 -->
<link rel="stylesheet" href="https://example.com/styles.css">
<!-- 链接到一个指定 Web 应用程序“安装”证书的 JSON 文件 -->
<link rel="manifest" href="manifest.json">
<!-- 链接到文档的作者 -->
<link rel="author" href="humans.txt">
<!-- 指向一个适用于链接内容的版权申明 -->
<link rel="copyright" href="copyright.html">
<!-- 给出可能的你的另一种语言的文档位置参考 -->
<link rel="alternate" href="https://es.example.com/" hreflang="es">
<!-- 提供了关于作者或其他人的信息 -->
<link rel="me" href="https://google.com/profiles/thenextweb" type="text/html">
<link rel="me" href="mailto:name@example.com">
<link rel="me" href="sms:+15035550125">
<!-- 链接到一个文档,包含当前文档的一个归档链接 -->
<link rel="archives" href="https://example.com/2003/05/" title="May 2003">
<!-- 链接到层次结构中的顶级资源 -->
<link rel="index" href="https://example.com/" title="DeWitt Clinton">
<!-- 给出该文档的起点 -->
<link rel="start" href="https://example.com/photos/pattern_recognition_1_about/" title="Pattern Recognition 1">
<!-- 引导当前文档的前述资源序列 -->
<link rel="prev" href="https://example.com/opensearch/opensearch-and-openid-a-sure-way-to-get-my-attention/" title="OpenSearch and OpenID? A sure way to get my attention.">
<!-- 给出一个自我参考 - 当文档有多个可能的参考时非常有用 -->
<link rel="self" type="application/atom+xml" href="https://example.com/atomFeed.php?page=3">
<!-- 分别是在一系列文件中的第一个、下一个、上一个和最后一个 -->
<link rel="first" href="https://example.com/atomFeed.php">
<link rel="next" href="https://example.com/atomFeed.php?page=4">
<link rel="previous" href="https://example.com/atomFeed.php?page=2">
<link rel="last" href="https://example.com/atomFeed.php?page=147">
<!-- 当使用第三方服务来维护 blog 时使用 -->
<link rel="EditURI" href="https://example.com/xmlrpc.php?rsd" type="application/rsd+xml" title="RSD">
<!-- 当另一个 WordPress 博客链接到你的 WordPress 博客或文章时形成一个自动化的评论 -->
<link rel="pingback" href="https://example.com/xmlrpc.php">
<!-- 当你在自己的页面上链接到一个 url 时通知它 -->
<link rel="webmention" href="https://example.com/webmention">
<!-- 加载一个外部的 HTML 文件到当前 HTML 文件中 -->
<link rel="import" href="component.html">
<!-- 打开搜索 -->
<link rel="search" href="/open-search.xml" type="application/opensearchdescription+xml" title="Search Title">
<!-- Feeds -->
<link rel="alternate" href="https://feeds.feedburner.com/example" type="application/rss+xml" title="RSS">
<link rel="alternate" href="https://example.com/feed.atom" type="application/atom+xml" title="Atom 0.3">
<!-- 预取,预载,预浏览 -->
<link rel="dns-prefetch" href="//example.com/">
<link rel="preconnect" href="https://www.example.com/">
<link rel="prefetch" href="https://www.example.com/">
<link rel="prerender" href="https://example.com/">
<link rel="preload" href="image.png" as="image">新增API
拖拽(Drag and Drop API)
代码
js
// 获取可拖动元素和目标元素
const draggable = document.getElementById('draggable');
const dropzone = document.getElementById('dropzone');
// 设置拖动事件
draggable.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', draggable.id);
});
// 设置放置事件
dropzone.addEventListener('dragover', (event) => {
event.preventDefault();
});
dropzone.addEventListener('drop', (event) => {
event.preventDefault();
const data = event.dataTransfer.getData('text');
const element = document.getElementById(data);
dropzone.appendChild(element);
});消息通知(Notification API)
代码
js
// 检查浏览器是否支持通知
if ('Notification' in window) {
// 请求通知权限
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
// 创建通知
new Notification('Hello!', {
body: 'This is a notification message.',
icon: 'icon.png'
});
}
});
}全屏API(Fullscreen API)
代码
js
// 获取元素
const element = document.getElementById('fullscreenElement');
// 进入全屏模式
function enterFullscreen() {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) { // Firefox
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) { // IE/Edge
element.msRequestFullscreen();
}
}
// 退出全屏模式
function exitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { // Firefox
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { // IE/Edge
document.msExitFullscreen();
}
}地理定位API(Geo location API)
代码
js
// 检查浏览器是否支持地理定位
if ('geolocation' in navigator) {
// 获取当前位置
navigator.geolocation.getCurrentPosition((position) => {
console.log(`Latitude: ${position.coords.latitude}, Longitude: ${position.coords.longitude}`);
}, (error) => {
console.error('Error occurred. Error code: ' + error.code);
});
} else {
console.log('Geolocation is not supported by this browser.');
}本地存储API(Local Storage API)
代码
js
// 存储数据
localStorage.setItem('key', 'value');
// 检索数据
const value = localStorage.getItem('key');
console.log(value);
// 删除数据
localStorage.removeItem('key');
// 清除所有数据
localStorage.clear();历史API(History API)
代码
js
// 添加历史记录
history.pushState({ page: 1 }, 'title 1', '?page=1');
// 替换当前历史记录
history.replaceState({ page: 2 }, 'title 2', '?page=2');
// 监听popstate事件
window.addEventListener('popstate', (event) => {
console.log('location: ' + document.location + ', state: ' + JSON.stringify(event.state));
});网络检测(Network Information API)
代码
js
const alertOnlineStatus = () => {
window.alert(navigator.onLine ? 'online' : 'offline')
}
window.addEventListener('online', alertOnlineStatus)
window.addEventListener('offline', alertOnlineStatus)
alertOnlineStatus()同源双工通讯(BroadcastChannel API)
- 同源内不同Tab页、frame、iframe之间简单的双工通讯
代码
js
//双方要使用同一个渠道名称的实例
var bc = new BroadcastChannel('test_channel');
// 发送简单消息的示例
bc.postMessage('This is a test message.');
// 消息订阅,用于将事件打印到控制台
bc.onmessage = function (ev) { console.log(ev); }
// 断开频道连接
bc.close()图形(WebGPU API)
- 简介:WebGPU 是一种新的图形 API,旨在提供更高效的 GPU 加速计算和图形渲染能力,作为 WebGL 的继任者。
- 用途:用于高性能图形渲染、数据可视化、机器学习等场景。
摄像头与麦克风(MediaDevices API)
- 获取媒体流:使用
navigator.mediaDevices.getUserMedia()方法请求访问用户的音频和视频设备。 - 列出可用设备:使用
navigator.mediaDevices.enumerateDevices()方法列出可用的媒体输入和输出设备。
Details
js
// 请求访问摄像头和麦克风
async function startMedia() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
const videoElement = document.querySelector('video');
videoElement.srcObject = stream; // 将媒体流绑定到视频元素
videoElement.play();
} catch (error) {
console.error('Error accessing media devices.', error);
}
}
startMedia();实时音视频通信(WebRTC API)
- 简介:WebRTC(Web Real-Time Communication)是一种用于实现实时音视频通信的 API。
- 用途:用于视频会议、实时聊天、P2P 文件共享等应用。
Details
js
// 创建 RTCPeerConnection
const peerConnection = new RTCPeerConnection();
// 添加本地媒体流
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
stream.getTracks().forEach(track => peerConnection.addTrack(track, stream));
});
// 处理远程流
peerConnection.ontrack = event => {
const remoteVideo = document.querySelector('#remoteVideo');
remoteVideo.srcObject = event.streams[0];
};
// 创建和发送 offer
peerConnection.createOffer()
.then(offer => peerConnection.setLocalDescription(offer))
.then(() => {
// 发送 offer 到远程对等方
});虚拟现实(VR)和增强现实(AR)(WebXR API)
- 简介:WebXR API 提供了对虚拟现实(VR)和增强现实(AR)设备的支持。
- 用途:用于创建沉浸式的 VR 和 AR 应用程序,增强用户体验。
Wasm (WebAssembly API)
- 简介:WebAssembly 是一种新的低级字节码格式,允许在 Web 上运行高性能的代码,支持多种编程语言(如 C、C++、Rust)。
- 用途:用于提高 Web 应用程序的性能,支持复杂的计算和游戏开发。
分享(Web Share API)
- 简介:Web Share API 允许用户通过系统的分享界面分享文本、链接和文件。
- 用途:用于简化内容分享,提升用户体验。
视口检测(Intersection Observer API)
- 简介:Intersection Observer API 允许开发者异步观察目标元素与其祖先元素或视口的交叉状态。
- 用途:用于实现懒加载、无限滚动和其他基于可见性的功能。
蓝牙通讯(Web Bluetooth)
- 简介:Web Bluetooth API 允许 Web 应用程序与蓝牙设备进行通信。
- 用途:用于与可穿戴设备、传感器等蓝牙设备交互。
后台运行(Service Workers)
- 简介:Service Workers 是一种在后台运行的脚本,允许开发者拦截和处理网络请求。
- 用途:用于实现离线功能、缓存资源、推送通知等。
支付(Payment Request API)
- 简介:Payment Request API 提供了一种标准化的方式来处理在线支付。
- 用途:用于简化电子商务网站的支付流程,提高用户体验。
USB设备通讯(HID API)
Details
js
// 请求访问 HID 设备
async function requestHID() {
const devices = await navigator.hid.requestDevice({ filters: [] });
if (devices.length > 0) {
const device = devices[0];
await device.open(); // 打开设备
console.log(`Connected to ${device.productName}`);
// 监听输入事件
device.addEventListener('inputreport', (event) => {
const { data } = event;
console.log('Input report received:', data);
});
}
}
// 调用请求函数
requestHID().catch(console.error);单方通讯(Beacon API)
- 适用于向服务器发送单方消息(数据埋点)
Details
js
navigator.sendBeacon(url);
navigator.sendBeacon(url, data);颜色吸管(EyeDropper API)
- 可以突破浏览器主体获取颜色
Details
js
document.getElementById("start-button").addEventListener("click", () => {
const resultElement = document.getElementById("result");
if (!window.EyeDropper) {
resultElement.textContent =
"Your browser does not support the EyeDropper API";
return;
}
const eyeDropper = new EyeDropper();
const abortController = new AbortController();
eyeDropper
.open({ signal: abortController.signal })
.then((result) => {
resultElement.textContent = result.sRGBHex;
resultElement.style.backgroundColor = result.sRGBHex;
})
.catch((e) => {
resultElement.textContent = e;
});
setTimeout(() => {
abortController.abort();
}, 2000);
});文件流(File API)
- 用于处理
input或拖拽获取的文件流 - 文件句柄
- Blob
- File
- FileList
- FileReader
- FileReaderSync
Details
js
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");
fileInput.addEventListener("change", () => {
const [file] = fileInput.files;
if (file) {
const reader = new FileReader();
reader.addEventListener("load", () => {
output.innerText = reader.result;
});
reader.readAsText(file);
}
});