关于前端:学会这些-Web-API-使你的开发效率翻倍

5次阅读

共计 13764 个字符,预计需要花费 35 分钟才能阅读完成。

随着浏览器的日益壮大,浏览器自带的性能也随着增多,在 Web 开发过程中,咱们常常会应用一些 Web API 减少咱们的开发效率。

本篇文章次要选取了一些乏味且有用的 Web API 进行介绍,并且 API 能够在线运行预览。

  • Clipboard API(剪切板)
  • Fullscreen API(进入 / 退出全屏)
  • Online State API(网络状态)
  • Page Visibility API(页面显示)
  • Screen Orientation API(页面方向)
  • Battery API(电池信息)
  • Web Share API(分享)
  • ImageCapture API(图片抓取)
  • Selection API(文本选区)
  • Performance API(性能检测)
  • Geolocation API(获取地位)
  • Broadcast Channel API(跨页面通信)
  • Vibration API(设施振动)
  • Srceen Capture API(视频截图)
  • Intersection Observer API(元素监听)

Clipboard API(剪切板)

剪切板 API 疾速将内容复制到剪切板上,上面是一键复制的办法:

const onClipText = (text) => {handleCopyValue(text)
        .then(() => {alert("复制胜利");
        })
        .catch(() => {alert("主动复制失败,请手动复制");
        });
};

const handleCopyValue = (text) => {
    // 浏览器禁用了非平安域的 navigator.clipboard 对象
    // 在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
    if (!navigator.clipboard && window.isSecureContext) {return navigator.clipboard.writeText(text);
    } else {
        // 判断是否反对拷贝
        if (!document.execCommand("copy")) return Promise.reject();
        // 创立标签,并暗藏
        const textArea = document.createElement("textarea");
        textArea.style.position = "fixed";
        textArea.style.top = textArea.style.left = "-100vh";
        textArea.style.opacity = "0";
        textArea.value = text;
        document.body.appendChild(textArea);
        // 聚焦、复制
        textArea.focus();
        textArea.select();
        return new Promise((resolve, reject) => {
            // 不知为何,必须写这个三目,不然 copy 不上
            document.execCommand("copy") ? resolve() : reject();
            textArea.remove();});
    }
};

执行 onClipText 办法,即可将想复制内容,复制到用户的剪切板上。

Fullscreen API(进入 / 退出全屏)

Fullscreen API 用于在 Web 应用程序中开启全屏模式,应用它就能够在全屏模式下查看页面 / 元素。在安卓手机中,它会溢出浏览器窗口和安卓顶部的状态栏(显示网络状态、电池状态等的中央)。

上面是一个 Fullscreen API 的例子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Fullscreen API Example</title>
  </head>
  <body>
    <div id="booktext">
       <h1> 正能量先锋 </h1>
        <p> 在明天这个快节奏、竞争强烈的时代里,咱们时常会面临一些挑战和艰难,有时甚至会让咱们感到失望和丧气。但咱们应该时刻铭刻,每一个艰难背地都有有限的机会和可能。</p>
       <button onclick="toggleFullscreen()"> 进入 / 退出沉迷式浏览 </button>
    </div>
    
    <script>
      var bookText = document.getElementById('booktext');
      
      function toggleFullscreen() {if (document.fullscreenElement) {document.exitFullscreen();
        } else {bookText.requestFullscreen().catch(err => {console.log(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
          });
        }
      }
    </script>
  </body>
</html>

下面的例子展现了如何通过 Fullscreen API 实现一个视频全屏播放的性能。

在 HTML 中,咱们定义了一个视频播放器,应用 controls 属性增加了播放器的管制栏。同时,咱们也定义了一个按钮,点击该按钮能够全屏播放视频。

在 JavaScript 中,咱们首先通过 getElementById 获取到视频容器,而后通过 querySelector 获取到视频元素自身。接着,定义了一个 toggleFullscreen 函数来监听按钮的点击事件,并依据以后全屏状态调用 requestFullscreenexitFullscreen 来切换全屏状态。

须要留神的是,requestFullscreen 办法可能会被浏览器阻止,例如因为用户未受权。因而在理论应用中,咱们须要应用 catch 办法来捕捉 requestFullscreen 办法的调用错误信息。

Online State API(网络状态)

就是获取以后的网络状态,同时也有对应的事件去响应网络状态的变动。

window.addEventListener("online", onlineHandler); // 联网时
window.addEventListener("offline", offlineHandler); // 断网时

比方很常见的一个需要,断网时提醒,网络复原时刷新。

实现断网重连:

const onlineHandler = () => {window.location.reload();
};
const offlineHandler = () => {alert("网络异样,请查看您的网络");
};
window.addEventListener("online", onlineHandler);
window.addEventListener("offline", offlineHandler);

这样就能够监听用户的网络状态,如网络链接、断开时能够对用户进行提醒以及做相应的逻辑解决。

Page Visibility API(页面显示)

咱们能够用 document.visibitilityState 来监听网页可见度,是否卸载..

在手机和电脑上都会现这种状况,比方页面中有一个视频正在播放,而后在切换 tab 页后给视频暂停播放,或者有个定时器轮询,在页面不显示的状态下进行无意义的轮询等等。

比方一个视频的例子来展现:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Fullscreen API Example</title>
  </head>
  <body>
 <video id="vs" src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" controls>
 </video>
<script>
const video = document.getElementById('vs')

window.addEventListener('visibilitychange',() => {
    // 通过这个办法来获取以后标签页在浏览器中的激活状态。switch(document.visibilityState){
        case'prerender': // 网页预渲染 但内容不可见
        case'hidden':    // 内容不可见 处于后盾状态,最小化,或者锁屏状态
        video.puase()
        case'visible':   // 内容可见
        video.play()
        case'unloaded':  // 文档被卸载
        video.destory()}
});
</script>
</body>
</html>

这个 API 的用途就是用来响应咱们网页的状态,如果这个标签页显示则视频就开始播放,暗藏就暂停,敞开就卸载。

Screen Orientation API(页面方向)

咱们能够通过以下代码来演示如何应用 Screen Orientation API 来管制页面的方向:

// 获取屏幕方向对象
const orientation = screen.orientation;

// 监听屏幕方向变动事件
orientation.addEventListener('change', () => {console.log(` 屏幕方向变为:${orientation.type}`);
});

// 锁定屏幕方向为横屏
orientation.lock('landscape').then(() => {console.log('屏幕方向已锁定为横屏');
}).catch((err) => {console.log(` 锁定屏幕方向失败:${err}`);
});

// 解锁屏幕方向
orientation.unlock();

在这段代码中,咱们首先通过 screen.orientation 获取了屏幕方向对象,并通过 addEventListener 办法监听了屏幕方向变动事件。而后,咱们应用 lock 办法将屏幕方向锁定为横屏,并在锁定胜利后打印了一条音讯。最初,咱们应用 unlock 办法解锁了屏幕方向。

须要留神的是,lock办法可能会在某些设施上无奈失效,因而咱们须要在理论应用中进行兼容性测试。

Battery API(电池信息)

以下是一个应用 Battery API 的简略示例:

<!DOCTYPE html>
<html>
<head>
    <title>Web Battery API Example</title>
</head>
<body>
    <h1>Web Battery API Example</h1>
    <div id="battery-status">
        <p> 以后电量: <span id="battery-level"></span></p>
        <p> 电池状态: <span id="battery-status"></span></p>
    </div>

    <script>
        // 获取电池信息
        navigator.getBattery().then(function(battery) {
            // 更新电量信息
            updateBatteryStatus(battery);

            // 监听电池信息变动
            battery.addEventListener('levelchange', function() {updateBatteryStatus(battery);
            });

            battery.addEventListener('chargingchange', function() {updateBatteryStatus(battery);
            });
        });

        // 更新电量信息
        function updateBatteryStatus(battery) {document.querySelector('#battery-level').textContent = battery.level * 100 + '%';
            document.querySelector('#battery-status').textContent = battery.charging ? '正在充电' : '未充电';
        }
    </script>
</body>
</html>

这个例子展现了如何应用 Web Battery API 来获取电池的状态信息,并在页面上显示以后电量和电池状态。

在这个例子中,咱们应用了 navigator.getBattery() 办法来获取电池信息,并应用 battery.addEventListener() 办法来监听电池信息变动。最初,咱们应用 updateBatteryStatus() 函数来更新电量信息并在页面上显示。

Web Share API(分享)

以下是一个简略的 Web Share API 例子:

// 获取分享按钮元素
const shareButton = document.querySelector('#share-button');

// 增加点击事件监听器
shareButton.addEventListener('click', async () => {
  try {
    // 查看浏览器是否反对 Web Share API
    if (navigator.share) {
      // 调用 Web Share API 分享
      await navigator.share({
        title: '分享题目',
        text: '分享形容',
        url: '分享链接'
      });
    } else {
      // 如果不反对,显示提示信息
      alert('该浏览器不反对 Web Share API');
    }
  } catch (error) {
    // 解决异常情况
    console.error('分享失败:', error);
  }
});

这个例子假如页面中有一个 id 为 share-button 的分享按钮元素。当用户点击该按钮时,代码会查看浏览器是否反对 Web Share API,如果反对则调用该 API 进行分享,否则显示一个提示信息。

navigator.share 办法中,咱们能够传递一个蕴含 titletexturl等属性的对象,用于指定分享内容的题目、形容和链接。如果用户抉择分享,零碎会弹出一个分享对话框,让用户抉择分享形式(例如通过社交媒体、电子邮件等形式分享)。

如果用户勾销分享,则 navigator.share 办法会返回一个 Promise 对象,其状态为 rejected。咱们能够通过捕捉该 Promise 对象的异样来解决分享失败的状况。

ImageCapture API(图片抓取)

以下提供一个根本的 Web ImageCapture API 示例,如下所示:

HTML 代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Web ImageCapture API Demo</title>
  </head>
  <body>
    <h1>Web ImageCapture API Demo</h1>
    <video id="video" width="640" height="480" autoplay></video>
    <br>
    <button id="capture-btn">Capture Image</button>
    <br>
    <canvas id="canvas" width="640" height="480"></canvas>
    <br>
    <img id="captured-img">
  </body>
</html>

JavaScript 代码:

// 获取视频和按钮元素
const video = document.getElementById('video');
const captureBtn = document.getElementById('capture-btn');

// 获取画布和图像元素
const canvas = document.getElementById('canvas');
const img = document.getElementById('captured-img');

// 获取视频流
navigator.mediaDevices.getUserMedia({video: true})
  .then(stream => {
    video.srcObject = stream;
    video.play();})
  .catch(error => {console.log(error);
  });

// 设置 ImageCapture
let imageCapture;
const track = video.srcObject.getVideoTracks()[0];
imageCapture = new ImageCapture(track);

// 增加事件监听器
captureBtn.addEventListener('click', () => {
  // 拍照
  imageCapture.takePhoto()
    .then(blob => {
      // 将照片显示在画布上
      const url = URL.createObjectURL(blob);
      canvas.getContext('2d').drawImage(img, 0, 0);
      
      // 将照片显示在图像元素中
      img.src = url;
    })
    .catch(error => {console.log(error);
    });
});

这个示例将显示一个视频元素和一个“Capture Image”按钮。当用户点击按钮时,它将应用 ImageCapture API 拍摄照片,并在画布和图像元素中显示照片。

请留神,此示例仅实用于反对 MediaStreamTrack 和 ImageCapture API 的浏览器。

Selection API(文本选区)

上面是一个 Web Selection API 的例子,如下所示:

HTML 代码:

<!DOCTYPE html>
<html>
<head>
    <title>Web Selection API Example</title>
    <style>
        .highlight {background-color: yellow;}
    </style>
</head>
<body>
    <h1>Web Selection API Example</h1>
    <p>Select text in the paragraph below to see the API in action.</p>
    <p id="demo">The Web Selection API allows you to retrieve and manipulate text selections made by the user.</p>
</body>
</html>

JavaScript 代码(web-selection-api.js):

// 获取文本节点
const demoEl = document.getElementById('demo');

// 监听文本节点的抉择事件
demoEl.addEventListener('mouseup', handleSelection);

// 解决抉择事件
function handleSelection() {
    // 获取用户抉择的文本
    const selection = window.getSelection();
    const selectedText = selection.toString();
    // 如果抉择的文本不为空
    if (selectedText) {
        // 创立一个新的高亮节点
        const highlightEl = document.createElement('span');
        highlightEl.classList.add('highlight');

        // 将高亮节点插入到抉择范畴中
        const range = selection.getRangeAt(0);
        range.surroundContents(highlightEl);

        // 勾销抉择
        selection.removeAllRanges();}
}

这个例子演示了如何应用 Web Selection API 来获取用户抉择的文本,并将其高亮显示。

当用户在页面上抉择文本时,会触发 mouseup 事件,而后调用 handleSelection 函数来解决抉择事件。

handleSelection 函数中,咱们首先应用 window.getSelection() 办法获取用户抉择的文本,而后查看是否抉择了文本。

如果抉择了文本,咱们创立一个新的 span 元素,并将其增加到抉择范畴中,而后应用 removeAllRanges() 办法勾销抉择。最初,咱们应用 CSS 款式将高亮显示的文本突出显示。

Performance API(性能检测)

以下是一个应用 Web Performance API 的例子:

// 测量页面加载工夫
const startTime = window.performance.now();

window.addEventListener('load', () => {const loadTime = window.performance.now() - startTime;
  console.log(` 页面加载工夫为:${loadTime} 毫秒 `);
});

// 测量网络工夫
const resourceUrl = 'https://example.com/resource';

fetch(resourceUrl)
  .then(response => {const fetchTime = window.performance.now() - startTime;
    console.log(` 申请工夫为:${fetchTime} 毫秒 `);

    // 获取网络工夫信息
    const entry = performance.getEntriesByName(resourceUrl)[0];
    const start = entry.fetchStart;
    const end = entry.responseEnd;

    console.log(`DNS 查问工夫为:${entry.domainLookupEnd - entry.domainLookupStart} 毫秒 `);
    console.log(`TCP 握手工夫为:${entry.connectEnd - entry.connectStart} 毫秒 `);
    console.log(`TLS 握手工夫为:${entry.secureConnectionStart ? entry.connectEnd - entry.secureConnectionStart : 'N/A'} 毫秒 `);
    console.log(` 申请工夫为:${entry.responseStart - entry.requestStart} 毫秒 `);
    console.log(` 响应工夫为:${entry.responseEnd - entry.responseStart} 毫秒 `);
    console.log(` 传输大小为:${entry.transferSize} 字节 `);
  });

在这个例子中,咱们应用了 Web Performance API 提供的 performance 对象来测量页面加载工夫和应用 fetch() 办法获取资源的网络工夫。咱们还应用了 getEntriesByName() 办法来检索资源的网络工夫信息。

Geolocation API(获取地位)

以下是一个应用 Geolocation API 获取用户以后地位信息的示例代码:

// 查看浏览器是否反对 Geolocation API
if ('geolocation' in navigator) {
  // 获取用户以后地位信息
  navigator.geolocation.getCurrentPosition((position) => {const { latitude, longitude} = position.coords;
      console.log(` 您的纬度为:${latitude},经度为:${longitude}`);
    },
    (error) => {switch (error.code) {
        case error.PERMISSION_DENIED:
          console.log('用户回绝了地位申请');
          break;
        case error.POSITION_UNAVAILABLE:
          console.log('无奈获取地位信息');
          break;
        case error.TIMEOUT:
          console.log('申请超时');
          break;
        default:
          console.log('产生未知谬误');
      }
    }
  );
} else {console.log('您的浏览器不反对 Geolocation API');
}

在这个例子中,咱们首先查看浏览器是否反对 Geolocation API

如果反对,则调用 navigator.geolocation.getCurrentPosition() 办法获取用户以后地位信息。该办法承受两个回调函数作为参数:一个胜利的回调函数和一个失败的回调函数。

如果获取地位信息胜利,则胜利的回调函数将被调用,并传递蕴含地位信息的对象作为参数。否则将调用失败的回调函数,并传递一个形容谬误的对象作为参数。

Broadcast Channel API(跨页面通信)

上面是一个应用 Broadcast Channel API 实现简略的跨窗口通信的例子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Broadcast Channel API Example</title>
  </head>
  <body>
    <div id="message"></div>
    <input type="text" id="input-message">
    <button onclick="sendMessage()">Send Message</button>

    <script>
      const channel = new BroadcastChannel('my-channel'); // 创立一个播送通道对象

      function sendMessage() {const inputMessage = document.getElementById('input-message');
        const message = inputMessage.value;
        channel.postMessage(message); // 将音讯发送到播送通道中
        inputMessage.value = ''; // 清空输入框内容
      }

      channel.onmessage = (event) => {
        const message = event.data;
        const messageDiv = document.getElementById('message');
        messageDiv.innerHTML = message;
      }
    </script>
  </body>
</html>

下面的例子展现了如何应用 Broadcast Channel API 实现在两个窗口之间进行文本音讯的双向通信。

在 HTML 中,咱们定义了一个输入框和一个按钮,用于输出和发送音讯。咱们还定义了一个 div 元素,用于展现接管到的音讯。

在 JavaScript 中,咱们创立了一个名为 my-channel 的播送通道对象,并定义了一个 sendMessage 函数,该函数将输入框中的文本音讯发送到播送通道中。

同时,咱们在 channel 对象上通过 onmessage 办法监听播送通道上的音讯,一旦有音讯发送到该通道,就会触发该办法,在该办法中将接管到的音讯展现在 div 元素中。

须要留神的是,播送通道的名字须要保持一致,能力实现不同窗口之间的通信。

Vibration API(设施振动)

以下是一个简略的 Web Vibration API 例子:

<!DOCTYPE html>
<html>
<head>
    <title>Web Vibration API Example</title>
</head>
<body>
    <h1>Web Vibration API Example</h1>
    <button onclick="vibrate()">Vibrate</button>
    <script>
        function vibrate() {if ("vibrate" in navigator) {navigator.vibrate(1000); // 1 秒钟的触动
            } else {alert("Vibration API not supported in this browser.");
            }
        }
    </script>
</body>
</html>

这个例子中,当用户点击 ”Vibrate” 按钮时,浏览器会尝试通过 Web Vibration API 来触发设施的触动性能。

如果设施反对 Web Vibration API,则会进行 1 秒钟的触动,否则会弹出一个正告框提醒用户该性能不被反对。

Srceen Capture API(视频截图)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Web Screen Capture API Example</title>
</head>
<body>
    <h1>Web Screen Capture API Example</h1>

    <button id="start-capture">Start Capture</button>
    <button id="stop-capture">Stop Capture</button>

    <canvas id="canvas" width="640" height="480"></canvas>

    <script>
        // 获取 DOM 元素
        const startCaptureBtn = document.getElementById('start-capture');
        const stopCaptureBtn = document.getElementById('stop-capture');
        const canvas = document.getElementById('canvas');

        // 获取媒体流(屏幕共享)并将其渲染到 canvas 中
        async function startCapture() {
            try {const mediaStream = await navigator.mediaDevices.getDisplayMedia();
                const context = canvas.getContext('2d');
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
            } catch(err) {console.error("Error:" + err);
            }
        }

        // 进行捕捉并进行媒体流
        function stopCapture() {const tracks = mediaStream.getTracks();
            tracks.forEach(track => track.stop());
        }

        // 注册按钮单击事件
        startCaptureBtn.addEventListener('click', startCapture);
        stopCaptureBtn.addEventListener('click', stopCapture);
    </script>
</body>
</html>

这个例子中,页面上有两个按钮,一个用于开始捕捉屏幕,另一个用于进行捕捉。捕捉的内容被出现在一个画布上。

startCapture() 函数中,咱们应用 navigator.mediaDevices.getDisplayMedia() 办法获取屏幕共享的媒体流,并将其渲染到 canvas 上。在 stopCapture() 函数中,咱们进行所有媒体流的所有轨道,以完结捕捉过程。

Intersection Observer API(元素监听)

以下是一个示例,演示了如何应用 Intersection Observer API 在元素进入视口时进行检测:

<!DOCTYPE html>
<html>
  <head>
    <title>Intersection Observer Example</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: green;
        margin-bottom: 50px;
      }
      .visible {background-color: red;}
    </style>
  </head>
  <body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>

    <script>
      const boxes = document.querySelectorAll('.box');

      const options = {
        rootMargin: '0px',
        threshold: 0.5
      };

      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {if (entry.isIntersecting) {entry.target.classList.add('visible');
          } else {entry.target.classList.remove('visible');
          }
        });
      }, options);

      boxes.forEach(box => {observer.observe(box);
      });
    </script>
  </body>
</html>

在这个示例中,咱们首先抉择所有具备“box”类的元素。而后,咱们创立一个带有 0 像素的 rootMargin 和 0.5 的阈值的 IntersectionObserver 实例。这意味着当元素的 50%位于视口内时,它将被视为可见。

而后,咱们循环遍历每个盒子元素,并在咱们的观察者实例上调用 observe 办法,将盒子元素作为参数传递。

最初,在 IntersectionObserver 实例的回调函数中,咱们查看每个条目是否与视口相交。如果是,则将“visible”类增加到条目标指标元素中,否则将其删除。

参考

  1. web-api-examples
  2. MDN-Web APIs
  3. 12 Rarely Used JavaScript Web APIs that Will Boost Your Website to THE MOON
  4. 7 JavaScript Web APIs to build Futuristic Websites you didn’t know
  5. 你(可能)不晓得的 web api

最初附上我的博客地址————九旬的博客,欢送🌟Star🌟。

正文完
 0