用户脚本在注入时不起作用,但在控制台中运行时起作用

问题描述 投票:0回答:1

我正在尝试制作一个用户脚本来向 youtube 添加下载按钮,我尝试了 tampermonkey 和 Greasemonkey,但它们不起作用。在控制台上手动运行时,脚本不会引发任何错误。当我将其复制并粘贴到控制台时,它会添加按钮。

用户脚本:

// ==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")
})();

我尝试将用户脚本扩展名从greasemonkey更改为tampermonkey,但都不起作用。 我尝试为 actionsdiv 编写一个 onload,但它也不起作用。

javascript greasemonkey tampermonkey userscripts
1个回答
0
投票

wOxxOm 关于需要等待元素出现在现代网站上的说法是正确的,但还有其他选择。

虽然 MutationObserver 绝对是在继续代码之前等待元素出现的正确方法,但还有更简单的方法 - 例如简单的

setTimeout()
(如下所示 - 不必要! - 下面)或使用 Promise 驱动的
sleep()
函数.

但是,对于您的测试用例来说,不需要任何这些。即使下面脚本中的

setTimeout
也不是必需的 - 没有它脚本也能工作。

试试这个方法:

// ==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( () => {
        //Give time for element to appear in 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>
    `;
}
© www.soinside.com 2019 - 2024. All rights reserved.