Home > Web Front-end > JS Tutorial > How Can I Detect and Modify YouTube Page Navigation Seamlessly?

How Can I Detect and Modify YouTube Page Navigation Seamlessly?

Mary-Kate Olsen
Release: 2024-12-04 05:24:11
Original
214 people have browsed it

How Can I Detect and Modify YouTube Page Navigation Seamlessly?

Integrating Seamless Page Modifications into YouTube Navigation

Detecting Page Navigation on YouTube

Unlike traditional websites that reload pages upon navigation, YouTube employs a technique that replaces the history state, avoiding content script reinjection.

Methods for Page Transition Detection

To detect page transitions on YouTube, consider these methods:

  • Background Script (MV3 Service Worker): Utilize the webNavigation API or the tabs API.
  • Content Script and navigatesuccess Event: Available in modern Chrome.
  • Content Script and YouTube's Custom Event: Leverage the 'yt-navigate-start' or 'yt-navigate-finish' event.

Implementing the Solution

manifest.json:

{
  "matches": ["*://*.youtube.com/*"],
  "js": ["content.js"],
  "run_at": "document_start"
}
Copy after login

content.js:

document.addEventListener('yt-navigate-start', process);
if (document.body) process();
else document.addEventListener('DOMContentLoaded', process);
Copy after login

Process Function for Page Modification:

function process() {
  if (!location.pathname.startsWith('/playlist')) return;
  var seconds = [...document.getElementsByClassName('timestamp')]
    .reduce((sum, ts) => {
      const minsec = ts.textContent.split(':');
      return sum + minsec[0] * 60 + minsec[1] * 1;
    }, 0);

  if (!seconds) {
    console.warn('Empty playlist');
    return;
  }

  const timeHMS = new Date(seconds * 1000)
    .toUTCString()
    .split(' ')[4]
    .replace(/^[0:]+/, '');

  document
    .querySelector('.pl-header-details')
    .insertAdjacentHTML('beforeend', `<li>Length: ${timeHMS}</li>`);
}
Copy after login

The above is the detailed content of How Can I Detect and Modify YouTube Page Navigation Seamlessly?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template