Audio won't be muted with JavaScript - removing audio tags with mutationobserver needed

耗尽温柔 提交于 2020-06-18 14:41:53

问题


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's addedNodes
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!