首页 > 解决方案 > 创建从 YouTube 中删除某些评论的用户脚本

问题描述

当人们对 YouTube 视频发表评论说他们正在“2018”或现在的任何年份观看视频时,或者询问其他正在做同样事情的人时,我觉得非常恼火。这样的评论通常会得到很多喜欢,因此保持在顶部附近。所以我开始制作一个脚本来删除所有这些评论。我编写了必要的代码并使用 Chrome 控制台成功测试。

问题是,我不知道如何让它运行/活跃,所以每当加载新评论或刷新页面时,这些评论都会被自动过滤掉。我使用了window.setTimeout但它只在评论已经加载时运行。不适用于新加载的评论。

任何帮助表示赞赏。以下是我的脚本:

// ==UserScript==
// @name         YouTube Comment Cleaner
// @namespace    iamMG
// @include      *://www.youtube.com/*
// @description  Remove keywords from YouTube comments.
// @author       iamMG
// @license      MIT
// @version      1.0
// ==/UserScript==

//Some code to detect when the element with id 'watch-discussion' becomes available.
//It is the parent element which contains all the comments.
window.setTimeout(function() {
    var expr = /20(15|16|17|18|19|20)/; //The text I want to detect in comments
    var commentText = document.getElementsByClassName('comment-renderer-text-content'); //The text element within each comment
    for (var i =0; i<commentText.length; i++) {
        if (expr.test(commentText[i].innerText)) {      //tests for the substring inside the comment text.
            var elem = commentText[i].parentNode.parentNode.parentNode.parentNode;  //elem is the actual comment element.
            console.log('removed '+ (i+1) + 'th comment');
            elem.parentNode.removeChild(elem);
            i--;
        }
    }
}, 4000)

标签: javascriptyoutubecommentsuserscripts

解决方案


最好把它写成一个扩展。您可以使用 chrome.alarms 来安排代码。如果使用 websockets 添加新评论,还可以检测 DOM 更改以判断是否添加了新评论。


推荐阅读