twain

twain

7 JavaScript Web APIs for building future websites that you may not know about 🤯

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! 🌕🚀

Screen Capture 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>
  Your browser does not support HTML5.
</video>
<button id="start" class="btn">Start</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 Share API#

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

async function shareHandler() {
  navigator.share({
    title: "Tapajyoti Bose | Portfolio",
    text: "Check out my website",
    url: "https://tapajyoti-bose.vercel.app/",
  });
}

Note: To use the Web Share API, you need user interaction, such as a button click or touch event.

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 personal preference, but you can use any framework or pure JavaScript.

Clipboard API#

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

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

Wake Lock API#

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

let wakeLock = null;

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

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

Note: The Wake Lock API only works when the page is already visible on the screen.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.