问题
I tried to use the following userscript to remove all audio from a certain website:
// ==UserScript==
// @name addicto
// @namespace nms
// @include http://*
// @include https://*
// @version 1
// @grant none
// ==/UserScript==
addEventListener('DOMContentLoaded', ()=>{
let sites = ['mako.co.il'];
let href = window.location.href;
for (let i = 0; i < sites.length; i++) {
if (href.includes(sites[i])) {
Array.prototype.slice.call(document.querySelectorAll('audio')).forEach((audio)=>{
audio.muted = true;
});
}
}
// If href includes the value of the iteration on the "sites" array, do stuff.
});
This code didn't work and I assume that observing all audio
tags coming randomly and mutating the DOM is exactly what I need to better cope with this.
How can this mutation observer be written? I have never written a mutation observer and I feel as if this example would be very short and very basic and exactly what I need to get a taste of the code context of the logic which I just described and I would thank dearly to anyone who will try to show it to me and other people who are having a similar problem.
回答1:
- Enumerate
mutations
and each mutation'saddedNodes
- Enumerate node's child elements because mutations are coalesced during page loading using the superfast getElementsByTagName instead of the superslow querySelectorAll
- Don't use
@grant none
, which runs your userscript in the page context, unless you really need direct access to the page's JavaScript objects - Use
@run-at document-start
to mute the audio during page loading
// ==UserScript==
// @name addicto
// @include *
// @run-at document-start
// ==/UserScript==
const sites = ['mako.co.il'];
if (sites.some(site => location.hostname.includes(site))) {
new MutationObserver(mutations => {
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.localName == 'audio') {
audio.muted = true;
} else if (node.firstElementChild) {
for (const child of node.getElementsByTagName('audio')) {
audio.muted = true;
}
}
}
}
}).observe(document, {subtree: true, childList: true});
}
来源:https://stackoverflow.com/questions/46844127/audio-wont-be-muted-with-javascript-removing-audio-tags-with-mutationobserver