观察者网用户评论屏蔽

帮你屏蔽你不想看到的用户的评论,防止被上头,节省时间挽救生命。

目前为 2019-08-25 提交的版本。查看 最新版本

// ==UserScript==
// @name     观察者网用户评论屏蔽
// @version  2.0
// @namespace     https://github.com/hefore/gczw
// @description   帮你屏蔽你不想看到的用户的评论,防止被上头,节省时间挽救生命。
// @author        hefore([email protected])
// @match    *://www.guancha.cn/*
// @match    *://user.guancha.cn/*
// -------- GREASEMONKEY API
// @grant       GM_xmlhttpRequest
// @grant       GM_download
// ------  GREASEMONKEY 4.0+ COMPATIBILITY
// @require     https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @grant       GM.xmlHttpRequest
// @grant       GM.download
// @run-at document-end
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';
  const DEBUG = false;
  const bindlog = console.log.bind(console, 'mt:');

  function applyLog() {
    bindlog.apply(this, arguments);
  }

  function blank() {}
  const log = DEBUG ? applyLog : blank;
  const hidecmd = '<span class="unfold">已被折叠,点击查看</span>';
  let myblacklist = [];
  let authorblacklist = [];
  let authorlist = [];
  let host = '';
  let path = '';

  const callback = function (mutationsList) {
    for (const mutation of mutationsList) {
      const type = mutation.type;
      switch (type) {
        case 'childList':
          log('A child node has been added or removed.');
          // debounce(queryComment, 1000, timerid);
          throttle(queryComment);
          break;
        case 'attributes':
          log(`The ${mutation.attributeName} attribute was modified.`);
          break;
        case 'subtree':
          log(`The subtree was modified.`);
          break;
        default:
          break;
      }
    }
  };
  const observer = new MutationObserver(callback);

  function handleLocalStorage(method, key, value) {
    switch (method) {
      case 'get': {
        const temp = window.localStorage.getItem(key);
        if (temp) {
          return temp;
        }
        return null;
      }
      case 'set': {
        window.localStorage.setItem(key, value);
        break;
      }
      case 'remove': {
        window.localStorage.removeItem(key);
        break;
      }
      default: {
        return null;
      }
    }
  }

  function addUserIntoBlacklist(ev) {
    if (myblacklist.indexOf(ev.target.dataset.uid) < 0) {
      myblacklist.push(ev.target.dataset.uid);
      handleLocalStorage('set', 'mylist', JSON.stringify(myblacklist));
    }
    log(myblacklist);
  }

  function toggleUserFromBlacklist(ev) {
    const index = myblacklist.indexOf(ev.target.dataset.uid);
    const cl = ev.target.closest('.comment-item');
    if (index >= 0) {
      myblacklist.splice(index, 1);
      handleLocalStorage('set', 'mylist', JSON.stringify(myblacklist));
      ev.target.innerHTML = '屏蔽';
      ev.target.dataset.blflag = false;
      cl.classList.remove('blacklistedmember');
    } else {
      myblacklist.push(ev.target.dataset.uid);
      handleLocalStorage('set', 'mylist', JSON.stringify(myblacklist));
      ev.target.innerHTML = '解除';
      ev.target.dataset.blflag = true;
      cl.classList.add('blacklistedmember');
    }
    log(myblacklist);
  }

  function queryComment() {
    // const userlist = [];
    const cl = document.getElementsByClassName('comment-item');
    observer.disconnect();
    Array.prototype.forEach.call(cl, v => {
      const user = v.querySelector('.user-avatar');
      // userlist.push(user.dataset.uid);

      if (
        myblacklist.indexOf(user.dataset.uid) >= 0 &&
        !user.classList.contains('blacklistedmember')
      ) {
        // console.log(user.nextElementSibling.innerText);
        // user.classList.add('blacklistedmember');
        // const texts = v.querySelectorAll('.comment-txt');
        // const text = texts[texts.length - 1];
        // const inner = text.innerHTML;
        // text.innerHTML = '';
        // const newnode = document.createElement('span');
        // newnode.innerHTML = inner;
        // newnode.style.cssText = 'display:none';
        // text.appendChild(newnode);
        // // newnode.insertAdjacentHTML('afterend', '<span class="unfold">点击显示</span>');
        // const anothernewnode = document.createElement('span');
        // anothernewnode.classList.add('unfold');
        // anothernewnode.innerHTML = '已被屏蔽,点击显示';
        // text.appendChild(anothernewnode);
        // text.classList.add('masked');
        v.classList.add('blacklistedmember');
      }
      if (user.classList.contains('addtoblacklist') === false) {
        const newnode = document.createElement('div');
        if (v.classList.contains('blacklistedmember')) {
          newnode.innerHTML = '解除';
        } else {
          newnode.innerHTML = '屏蔽';
        }
        newnode.addEventListener('click', toggleUserFromBlacklist);
        // newnode.style.cssText = elemtoinsert;
        newnode.dataset.uid = user.dataset.uid;
        newnode.dataset.blflag = true;
        newnode.classList.add('blbtn');
        user.appendChild(newnode);
        user.classList.add('addtoblacklist');
      }
    });

    const cim = document.getElementsByClassName('cmt-item-main');
    Array.prototype.forEach.call(cim, v => {
      const quotea = v.querySelector('span.quote a');
      const text = quotea.href;
      const regex = new RegExp('uid=(\\d+)$');
      const match = regex.exec(text)[1];
      if (
        myblacklist.indexOf(match) >= 0 &&
        !v.classList.contains('blacklistedmemberq')
      ) {
        v.classList.add('blacklistedmemberq');
      }
    });

    startObserber();
  }

  function throttle(method, scope) {
    clearTimeout(method.tId);
    method.tId = setTimeout(() => {
      method.call(scope);
    }, 277);
  }

  function startObserber() {
    // const container = document.getElementById('comments-container');
    const targetNode = document.querySelector(`#comments-container`);
    const config = {
      attributes: false,
      childList: true,
      subtree: true
    };
    if (targetNode) {
      observer.observe(targetNode, config);
    }
    // log(container);
  }

  function initcss() {
    const style = document.createElement('style');
    style.innerHTML = `
      .blbtn {margin: 10px 0px;border: 2px solid;padding: 2px 5px;border-radius: 3px;
        font-size: 80%;cursor: pointer;background-color: ivory;}
      .blbtn:hover {background-color: MistyRose;}
      .blacklistedmember .blbtn {background-color: azure;}
      .blacklistedmember .blbtn:hover {background-color: burlywood;}
      .blacklistedmember .user-avatar > img {filter: blur(2px);}
      .blacklistedmember .user-avatar > img:hover {filter: blur(0);}
      .blacklistedmember .user-nick {filter: blur(2px);}
      .blacklistedmember .user-nick:hover {filter: blur(0);}
      .blacklistedmember .signature {filter: blur(2px);}
      .blacklistedmember .signature:hover {filter: blur(0);}
      .blacklistedmemberq span a {filter: blur(2px);}
      .blacklistedmemberq span a:hover {filter: blur(0);}
      .blacklistedmemberq .comment-txt {filter: blur(2px);}
      .blacklistedmemberq .comment-txt:hover {filter: blur(0);}
      @keyframes appear {from {filter: blur(5px);} to{filter: blur(0);}}
      .blacklistedmember > div:nth-last-of-type(2) {filter: blur(5px);}
      .blacklistedmember > div:nth-last-of-type(2):hover {animation:appear 1s 2s forwards;}
      .blockedauthor {filter: blur(5px);}
      .blockedauthor:hover {animation:appear 1s 2s forwards;}
      .aubtn {margin: 0px;border: 2px solid;padding: 2px 5px;border-radius: 3px;
        font-size: 80%;cursor: pointer;background-color: ivory;display: inline-block;
        bottom: 0px;line-height: 14px;position: absolute;right: 0px;}
      .aubtn:hover {background-color: MistyRose;}
      `;
    const head = document.head || document.getElementsByTagName('head')[0];
    head.appendChild(style);
  }

  function maskArticle(flag) {
    const atc = document.getElementsByClassName('article-txt-content')[0];
    if (flag) {
      atc.classList.add('blockedauthor');
    } else {
      atc.classList.remove('blockedauthor');
    }
  }

  function addAuthorlist(ev) {
    ev.preventDefault();
    const index = authorblacklist.indexOf(ev.target.dataset.id);
    if (index >= 0) {
      authorblacklist.splice(index, 1);
      handleLocalStorage('set', 'authorlist', JSON.stringify(authorblacklist));
      ev.target.innerHTML = '屏蔽此人';
      ev.target.dataset.blflag = false;
      maskArticle(false);
      // cl.classList.remove('blacklistedmember');
    } else {
      authorblacklist.push(ev.target.dataset.id);
      handleLocalStorage('set', 'authorlist', JSON.stringify(authorblacklist));
      ev.target.innerHTML = '解除屏蔽';
      ev.target.dataset.blflag = true;
      maskArticle(true);
      // cl.classList.add('blacklistedmember');
    }
    console.log(authorblacklist);
    return false;
  }

  function initBlacklist() {
    const storagedata = handleLocalStorage('get', 'mylist') || '[]';
    myblacklist = JSON.parse(storagedata);
    // console.log(myblacklist);
    const storagedataa = handleLocalStorage('get', 'authorlist') || '[]';
    authorblacklist = JSON.parse(storagedataa);
    console.log(authorblacklist);
  }

  function fengWenInitBtn() {
    if (host !== 'user.guancha.cn') {
      log(' not a fengwen article!');
      return;
    }
    const abu = document.querySelector('.article-bottom-user');
    if (abu !== null) {
      const ua = abu.getElementsByClassName('attention')[0];
      const a = document.createElement('a');
      const index = authorblacklist.indexOf(ua.dataset.id);
      if (index < 0) {
        a.innerText = '屏蔽此人';
      } else {
        a.innerText = '解除屏蔽';
        maskArticle(true);
      }
      a.href = '#';
      a.addEventListener('click', addAuthorlist);
      a.classList.add('btn');
      a.style.right = '100px';
      a.dataset.id = ua.dataset.id;
      // const textnode = document.createTextNode('屏蔽此人');
      // a.appendChild(textnode);
      abu.appendChild(a);
    }
  }

  function fenwen24GetAuthorList() {
    // eslint-disable-next-line no-undef
    GM.xmlHttpRequest({
      method: 'GET',
      headers: {
        'If-Modified-Since': 0
      },
      url: 'https://user.guancha.cn/main/index-list?page=1&order=3',
      onload: response => {
        // console.log(response.responseText);
        if (response.responseText === '') {
          log('fenwen24GetAuthorList cached');
        } else {
          const d = document.createElement('div');
          d.innerHTML = response.responseText;
          const ilis = d.getElementsByClassName('index-list-item');
          if (ilis.length > 10) {
            const res = [];
            // log('index-list-item:' + ilis.length);
            for (let i = 0; i < ilis.length; i++) {
              const ili = ilis[i];
              const userId = ili
                .getElementsByClassName('user-avatar')[0]
                .getAttribute('user-id');
              const articleId = ili.getElementsByClassName('shared-box')[0]
                .dataset.id;
              res.push([articleId, userId]);
            }
            authorlist = res;
            handleLocalStorage(
              'set',
              'authorsOfArticles',
              JSON.stringify(authorlist)
            );
            console.log(res);
          }
        }
      }
    });
    const storagedata = handleLocalStorage('get', 'authorsOfArticles') || '[]';
    authorlist = JSON.parse(storagedata);
    console.log(authorlist);
  }

  const fwcallback = function (mutationsList) {
    for (const mutation of mutationsList) {
      if (mutation.type === 'childList') {
        console.log(mutation.addedNodes);
        fenwen24filterHandler(mutation.addedNodes);
      }
    }
  };
  const fwobserver = new MutationObserver(fwcallback);

  function add2Authorlist(ev) {
    const index = authorblacklist.indexOf(ev.target.dataset.uid);
    const cl = ev.target.closest('.fenwen24-box');
    if (index >= 0) {
      authorblacklist.splice(index, 1);
      handleLocalStorage('set', 'authorlist', JSON.stringify(authorblacklist));
      ev.target.innerHTML = '屏蔽';
      ev.target.dataset.blflag = false;
      // maskArticle(false);
      cl.classList.remove('blockedauthor');
    } else {
      authorblacklist.push(ev.target.dataset.uid);
      handleLocalStorage('set', 'authorlist', JSON.stringify(authorblacklist));
      ev.target.innerHTML = '解除';
      ev.target.dataset.blflag = true;
      // maskArticle(true);
      cl.classList.add('blockedauthor');
    }
    console.log(authorblacklist);
  }

  function fenwen24filterHandler(nl) {
    fwobserver.disconnect();
    nl.forEach(dv => {
      const a = dv.getElementsByClassName('fenwen24-title')[0];
      const regex = new RegExp('id=(\\d+)');
      const match = regex.exec(a.href)[1];
      const author = authorlist.find(v => {
        return v[0] === match;
      });
      log(author);
      const index = authorblacklist.indexOf(author[1]);
      let btntext = '屏蔽';
      if (index >= 0) {
        dv.classList.add('blockedauthor');
        btntext = '解除';
      }
      const bx = dv.getElementsByClassName('fenwen24-box-right')[0];
      const newnode = document.createElement('div');
      newnode.innerHTML = btntext;
      newnode.addEventListener('click', add2Authorlist);
      // newnode.style.cssText = elemtoinsert;
      newnode.dataset.uid = author[1];
      newnode.dataset.blflag = true;
      newnode.classList.add('aubtn');
      bx.appendChild(newnode);
    });
  }

  function fenwen24Filter() {
    const fw24 = document.getElementsByClassName('fenwen24')[0];
    if (fw24) {
      log('fw24 exist');
      // fw24.addEventListener('DOMNodeInserted', fenwen24filterHandler);
      const config = {
        childList: true,
        subtree: true
      };
      fwobserver.observe(fw24, config);
      fenwen24GetAuthorList();
    }
  }

  // 初始化
  function init() {
    host = window.location.host;
    path = window.location.pathname;
  }

  init();
  initBlacklist();
  initcss();
  startObserber();
  fengWenInitBtn();
  fenwen24Filter();
  // fenwen24GetAuthorList();
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址