The Userscript fails to function when injected, but operates successfully when executed in the console

I've been attempting to create a userscript that adds a download button to YouTube. I initially tried using Tampermonkey and Greasemonkey, but unfortunately, they were ineffective. Strangely enough, the script runs without any errors when manually executed in the console. The button is successfully added when I copy and paste the script directly into the console.

Here is the userscript:

// ==UserScript==
// @name         Youtube Downloader
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Download Youtube Videos With One Click!
// @author       qweren
// @match        https://www.youtube.com/*
// @icon         https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/YouTube_full-color_icon_%282017%29.svg/1024px-YouTube_full-color_icon_%282017%29.svg.png
// ==/UserScript==

(function() {
    'use strict';

    // Check if the "actions" div exists
    var actionsDiv = document.getElementById('actions');
    // Create a new button element
    var newButton = document.createElement('button');
    newButton.textContent = 'Click Me';

    // Add an event listener to the button
    newButton.addEventListener('click', function() {
        alert('Button clicked!');
    });

    // Append the button to the "actions" div
    actionsDiv.appendChild(newButton);
    console.log("adding button")
})();

I attempted switching between Greasemonkey and Tampermonkey extensions, both of which failed to work. Additionally, trying to implement an onload function for the actionsdiv also proved unsuccessful.

Answer №1

wOxxOm makes a valid point regarding the importance of waiting for elements to appear on modern websites, but there are alternative approaches.

While MutationObserver is considered the optimal method for pausing code execution until elements are present, there exist simpler techniques like utilizing a basic setTimeout() function (as showcased - albeit unnecessarily - below) or integrating a Promise-based sleep() function.

In this particular scenario, none of these methods are actually required. Even the presence of the setTimeout in the subsequent script is redundant as the script functions correctly without it.

Consider employing the following strategy:

// ==UserScript==
// @name         Youtube Downloader
// @namespace    ErensScripts
// @version      0.1
// @description  Download Youtube Videos With One Click!
// @author       qweren
// @match        https://www.youtube.com/*
// ==/UserScript==

(function() {
    'use strict';

    const $ = document.querySelector.bind(document);
    $('body').insertAdjacentHTML('beforeend', init() );

    setTimeout( () => {
        //Allow time for element to be added to DOM...
        $('#myButt').addEventListener('click', () => { 
            alert('Thanks!');
        });
    },100);


})();
function init(){
    return `
    <button id='myButt' class="myfix">Scratch Me</button>
    <style>
        .myfix{position:fixed;top:0;right:10%;}
        #myButt{font-size:5rem;color:yellow;background:firebrick; z-index:99999;}
    </style>
    `;
}

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

The oninput event in IE10 is consistently triggered upon redirection

I have encountered a strange issue with IE10 when redirecting the page on an 'oninput' event, which does not occur with Chrome. I have simplified the code to demonstrate the problem: <html> <head> <script type="text/javascript&g ...

What is the process for resetting a function within an AJAX Response?

I have implemented the code below in AJAX to switch tabs. $("a").click(function(event){ if ($.browser.msie != true && $.browser.version != 8.0){ event.preventDefault(); if ($(this).parent().hasClass("current") == false){ ...

Execute code after the directive has finished loading

Currently, I am facing an issue with a function that handles resizing after a directive is loaded. The function always runs before the content in the directive is fully loaded, causing it not to resize properly. Here is a snippet of the code I am working ...

$http promise chain executing in an incorrect sequence

As a beginner in angularjs, my objective is straightforward. I aim to execute an ajax request to fetch data and, upon completion, I want to initiate a second call to retrieve another set of data based on the information from the initial set. To achieve th ...

Guide to sending checkbox data using jQuery AJAX

I am facing an issue with submitting the form below: <form action="/someurl" method="post"> <input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5"> <input type="checkbox" class="mychoice" name="name" value="appl ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...

Incorporating Event Listeners for Controlling Playback and Navigation in HTML5 Video

I am trying to integrate an HTML5 video into my website to demonstrate how a product works. Each time a user clicks on an image, I want the video to skip to a specific time and then pause at another predefined time. However, the code I have implemented so ...

Tips for accessing an Element by its Id in Vue

I am trying to access an external Element in Vue by using the method getElementById(): new Vue({ el: "#vue", data: { helloElement: document.getElementById('hello') } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/v ...

What strategies can be implemented to decrease the initial loading duration of a YouTube iframe video?

What are some techniques we can use to decrease iframe loading time? Is it possible to implement lazy loading for YouTube iframe videos? I experimented with initially hiding the iframe and displaying an image instead. However, when the user clicks, it req ...

The entire component is not displayed in Vue

Just starting out with Vue. I'm looking to create a component that encompasses the entire page except for the header and footer Vue.component('main-block', {template: ` <section id="first-block">...</section> <secti ...

Utilizing Vue.js to add functionality for navigation buttons allowing users to move between survey questions

In my Vue.js component, I've written code to show survey questions in a mobile app for users. Here is a snippet of the code: <div class="col-12 p-0" v-for="( i, index ) in questions" :key="i"> <p cl ...

Refreshing the Dropdown Menu with Jquery

Looking for a way to create a reusable dropdown menu using css/jquery? Check out this codepen: https://codepen.io/anon/pen/NxXXPg Is there a method to reset the 'active' status when clicking on a blank space or another html element? Here's ...

Is there a way to link a number with a particular string and apply that string as a filter for iteration in AngularJS?

I've recently started learning AngularJS and I'm facing challenges with creating a reusable generic filter. Let's consider the colors, types, and list objects outlined in the new JSON below. I aim to develop a generic filter that can take t ...

Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan. Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly. For instance, if someone submits August 21 and 200, I w ...

Tips for adjusting the height of a cell or row in a wijmo grid using a dynamically assigned id

I've been attempting to increase the row height of a wijmo grid with no success. Despite consulting the official documentation which suggests adding padding to the css of the grid cells, I'm facing an issue because the id is dynamic and not fixed ...

JavaScript class errors due to undeclared variables

I'm currently facing challenges with implementing and understanding classes in JavaScript. My experimentation involves a simple app that I created with the objective of extracting names from a textarea, storing them in an array, and then performing va ...

What is the best way to store the JSON data that is returned in a JavaScript function as a variable

My goal is to save the client's IP address in a variable after fetching it in JSON format from api.ipify.org. I have managed to display the IP if I alert the result, but I am struggling to store it in a variable. This code snippet works: <script& ...

Tips for effectively managing ajax timeouts

Consider this scenario: a user attempts to log in, but encounters slow connection or network issues causing the request to become stuck. In such cases, it might be more efficient to resend the request rather than waiting indefinitely. Queries: What is t ...

Does Visual Studio Code support custom procedural import paths for JavaScript intellisense?

I am looking to implement JS (ESM) intellisense for vscode within the Firefox codebase for a specific distribution of Firefox. Within Firefox, I need to register modules in build scripts like moz.build and import them using paths such as "resource://gre/m ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...