I'm making a simple Chrome extension for YouTube. I've succeeded at that, but my script only works after refreshing a page. YouTube site doesn't reload pages on navigation. The extension's content scripts aren't reinjected when URL changes without a page being reloaded. Naturally when I reload a page manually the content script is executed.
How to run the content script when the site is navigated?
window.addEventListener('load', function(){
function injectScript() {
if(document.querySelector('#a') === null && document.querySelector('#player.style-scope') !== null){
Array.from(document.querySelectorAll('#player')).pop().insertAdjacentHTML("afterend", `<div id="a" style="color:red">Code</div>`);
// Code
}
}
const element = document.querySelector('body');
function childList(list){
injectScript();
}
let callback = function(mutations, observer) {
mutations.forEach(function(mutation) {
if(mutation.type === 'childList'){
childList(mutation);
}
});
}
const mutationObserver = new MutationObserver(callback);
const config = {
childList: true,
subtree: true
};
mutationObserver.observe(element, config);
})