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:
Implementing the Solution
manifest.json:
{ "matches": ["*://*.youtube.com/*"], "js": ["content.js"], "run_at": "document_start" }
content.js:
document.addEventListener('yt-navigate-start', process); if (document.body) process(); else document.addEventListener('DOMContentLoaded', process);
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>`); }
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!