Preventing audio from being muted using JavaScript requires the removal of audio tags through a MutationObserver

I attempted to utilize the script below to eliminate all audio from a specific 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 script did not successfully remove the audio, leading me to believe that using a mutation observer to handle randomly incoming audio tags and DOM manipulation might be a more effective approach.

Could someone provide a simple example of how to write a mutation observer for this purpose? I am new to mutation observers, and I believe a basic example like this would greatly help me and others facing a similar issue to better understand the logic and context of the code. Thank you in advance to anyone willing to provide guidance.

Answer №1

  • List down the different mutations along with the addedNodes for each mutation
  • Enumerate child elements of nodes as mutations are combined during page load using the efficient getElementsByTagName instead of the slower querySelectorAll
  • Avoid using @grant none unless necessary for direct access to page JavaScript objects
  • Use @run-at document-start to mute audio playback while the page is 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});
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Typescript occurrence when combining multiple optional types

This code snippet illustrates a common error: interface Block { id: string; } interface TitleBlock extends Block { data: { text: "hi", icon: "hi-icon" } } interface SubtitleBlock extends Block { data: { text: &qu ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Encountering a TypeError when attempting to read the property 'name' of undefined while submitting a form in node.js

I'm currently working on a node Js project and I'm encountering an issue while saving form values to a mongoDB database. I've been troubleshooting but can't seem to pinpoint the cause of this error. The error is occurring at the router. ...

Using Rails 6 to trigger a JavaScript function after rendering a partial

Newbie in Rails and Javascript here, During a training project, I implemented a feature where flash messages automatically disappeared after a few seconds using JQuery. When a visitor added a product to their cart through an AJAX request, a flash partial ...

Looking to incorporate HTML5 videos into a responsive Bootstrap carousel?

I've been working on creating a carousel that includes videos. When it comes to images, everything works smoothly as they are responsive even in mobile view. However, I'm encountering an issue with videos where the width is responsive but the hei ...

What could be causing the malfunction of the v-bind attribute?

I am in the process of developing a straight-forward To-Do List application with VueJS. <template> <div> <br/> <div id="centre"> <div id="myDIV" class="header"> <h2 style="margin:5px">M ...

What is the method for setting autofocus to the first input element within a loop?

I am currently working on a loop to display inputs, and I would like to be able to add focus to the first input element when it is clicked. Does anyone have any suggestions on how I can select that first element and set autofocus on it? ...

JavaScript method overloading involves defining multiple functions with the same name

In my JavaScript code, I have implemented method overloading using the following approach: function somefunction() { //1st function } function somefunction(a) { //2nd function } function somefunction(a,b) { //3rd function } somefunction(); // ...

Using jQuery and Ajax to fade in content after all images and other assets have finished loading

I've encountered an issue with loading pages via ajax for users with custom URLs. For example, a profile is usually found at http://example.com/users/Dan, but if a user has a custom URL like http://example.com/DansCustomURL, I need to fetch their desi ...

"Issue with Material-ui Autocomplete where the defaultValue does not function properly

The defaultValue was set to "Chairs" but it doesn't seem to be working as expected. Here is the code snippet: import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from "@mui/material/Autocomple ...

Craft a hierarchical JSON structure out of a different nested JSON object [PAUSE]

Looking to transform an existing JSON object into a new object structure. Here is the current JSON object: { "name": "Parent", "children": [ { "name": "Child1", "children": [ { "name": "GrandC ...

Issues encountered when utilizing a provider alongside a controller for implementing Highcharts visualizations in angularjs

I've been working on an Angular web application that incorporates highcharts (highcharts-ng) integration. My approach was to set up a factory provider where I defined my chart configuration options object: angular.module('socialDashboard') ...

IE is failing to trigger jAlert function

When I validate a text box by pressing the enter key on my keyboard, the validation works fine but the JAlert doesn't show up. However, when I call the same function on a button click, the alert shows in IE. I am quite confused by this behavior and wo ...

Combining Components in NextJs Without Using Functional Components

I created a module, then split it into components and now I'm trying to piece it back together. The individual components are functioning correctly. Some components are nested inside the div of another component. I attempted to group them within a d ...

Is it advisable to incorporate both Jquery and AngularJs into progressive web applications?

Currently, I am in the process of constructing a progressive test application. So far, all the tutorials I have come across utilize native JavaScript. My inquiry is whether it is possible to leverage Jquery for streamlined code writing and implement an MVC ...

Zooming does not activate the onZoom event

I have created a line chart using react-chartjs-2 and incorporated the chartjs-plugin-zoom plugin. My goal is to have the zoom level displayed in the console whenever the chart is zoomed in or out. However, it seems that the onZoom function is not being tr ...

I am facing an issue where the HTML button is not properly interacting with the JavaScript function

function idk() { let cypher = {A:"G",B:"L",C:"Z",D:"E",E:"Y",F:"R",G:"D",H:"N",I:"K",J:"W",K:"J",L:"B",M:"Q",N:"F",O:"S",P:"C",Q:"V",R:"X",S:"I",T:"O",U:"M",V:"T",W:"A",X:"U",Y:"H",Z:"P"}; var answer = prompt('What cypher are you going to use 1 - 26& ...

The save feature becomes dysfunctional after switching to the Material-UI dependency in a React project

After integrating the Material-UI dependency into my ReactJS code, I encountered an issue where the "save" functionality no longer works properly. Previously, when editing a task in my simple Todo list app, the new name would be saved successfully. However ...

Manipulating CSS animations through JQuery

Currently, my animation is triggered by a :hover event. However, I would like to change it so that the animation starts when a button is clicked. Can someone guide me on how to manipulate the CSS using JQuery? //CSS .mouth{ top: 268px; left: 273px; ...

React Application Issue 'Error: React is not defined'

I've been working on developing an app using react, but for some reason, it's not functioning properly and I'm struggling to pinpoint the issue. The code compiles without errors using babelify, however, it throws an exception during executio ...