twain

twain

未来のウェブサイトを構築するための7つのJavaScript Web API、あなたは知らないかもしれません🤯

With the rapid development of technology, developers have gained incredible new tools and APIs. However, a survey found that out of over 100 APIs, only 5% are actively used by developers.

Let's take a look at some useful Web APIs that can help your website soar to new heights! 🌕🚀

スクリーンキャプチャ API#

As the name suggests, the Screen Capture API allows you to capture the content of your screen, making it easy to build a screen recorder. You need a video element to display the captured screen. Clicking the start button will initiate the screen capture.

<video id="preview" autoplay>
  あなたのブラウザはHTML5をサポートしていません。
</video>
<button id="start" class="btn">開始</button>
const previewElem = document.getElementById("preview");
const startBtn = document.getElementById("start");

async function startRecording() {
  previewElem.srcObject = await navigator.mediaDevices.getDisplayMedia({
    video: true,
    audio: true,
  });
}

startBtn.addEventListener("click", startRecording);

Web 共有 API#

The Web Share API allows you to share text, links, and even files from your web page to other applications installed on your device.

async function shareHandler() {
  navigator.share({
    title: "Tapajyoti Bose | ポートフォリオ",
    text: "私のウェブサイトを見てください",
    url: "https://tapajyoti-bose.vercel.app/",
  });
}

Note: To use the Web Share API, you need user interaction, such as button clicks or touch events.

Intersection Observer API#

The Intersection Observer API allows you to detect when an element enters or leaves the viewport. This is useful for implementing infinite scrolling.

const MAX_PAGES = 5;

const generateRandomColor = () => {
  const characters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += characters[Math.floor(Math.random() * 16)];
  }
  return color;
};

const Item = ({ children, color, reference }) => {
  return (
    <div className="item" style={{ backgroundColor: color }} ref={reference}>
      {children}
    </div>
  );
};

const App = () => {
  const [items, setItems] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [hasMore, setHasMore] = React.useState(true);
  const [pages, setPages] = React.useState(0);
  const observer = React.useRef();

  React.useEffect(() => {
    updateItems();
    setPages((pages) => pages + 1);
  }, []);

  const lastItemRef = React.useCallback(
    (node) => {
      if (isLoading) return;
      if (observer.current) observer.current.disconnect();

      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          if (pages < MAX_PAGES) {
            updateItems();
            setPages((pages) => pages + 1);
          } else {
            setHasMore(false);
          }
        }
      });

      if (node) observer.current.observe(node);
    },
    [isLoading, hasMore]
  );

  const updateItems = async () => {
    setIsLoading(true);
    await new Promise((resolve) => setTimeout(resolve, 1000));

    setItems((currItems) => {
      const lastItem = currItems.length;
      const updatedItems = [...currItems];
      for (let i = 1; i <= 5; i++) {
        const item = {
          count: lastItem + i,
          color: generateRandomColor()
        };
        updatedItems.push(item);
      }
      return updatedItems;
    });

    setIsLoading(false);
  };

  return (
    <React.Fragment>
      <h1>Infinite Scroll Demo</h1>
      {items.map((item, index) =>
        index + 1 === items.length ? (
          <Item reference={lastItemRef} key={index} color={item.color}>
            {item.count}
          </Item>
        ) : (
          <Item key={index} color={item.color}>
            {item.count}
          </Item>
        )
      )}
      {isLoading && <div className="loader" />}
    </React.Fragment>
  );
};

const root = document.getElementById("root");
ReactDOM.render(<App />, root);

Note: The example uses React because of my personal preference, but you can use any framework or pure JavaScript.

クリップボード API#

The Clipboard API allows you to read and write data to the clipboard. This is useful for implementing copy to clipboard functionality.

async function copyHandler() {
  const text = "https://tapajyoti-bose.vercel.app/";
  navigator.clipboard.writeText(text);
}

スクリーンウェイクロック API#

Have you ever wondered how YouTube prevents the screen from being turned off while playing a video? This is thanks to the Screen Wake Lock API.

let wakeLock = null;

async function lockHandler() {
  wakeLock = await navigator.wakeLock.request("screen");
}

async function releaseHandler() {
  await wakeLock.release();
  wakeLock = null;
}

Note: This API only works when the page is already visible on the screen.

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。