Twitter/X Search Filter (Simple)

Filter Twitter/X search results by keywords or accounts

  1. // ==UserScript==
  2. // @license MIT
  3. // @name Twitter/X Search Filter (Simple)
  4. // @namespace http://tampermonkey.net/
  5. // @version 0.1
  6. // @description Filter Twitter/X search results by keywords or accounts
  7. // @author Grok
  8. // @match *://twitter.com/*
  9. // @match *://x.com/*
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. // 配置:需要过滤的关键词和账户
  17. const filterConfig = {
  18. keywords: ['广告', '推广', 'spam'], // 需要屏蔽的关键词
  19. accounts: ['example_user', 'bot_account'], // 需要屏蔽的账户(@用户名,去掉@)
  20. hideStyle: 'opacity: 0.3;' // 隐藏样式(可改为 'display: none;' 完全隐藏)
  21. };
  22.  
  23. // 主过滤函数
  24. function filterTweets() {
  25. // 获取所有推文元素
  26. const tweets = document.querySelectorAll('article[data-testid="tweet"]');
  27. tweets.forEach(tweet => {
  28. try {
  29. // 获取推文文本
  30. const text = tweet.textContent.toLowerCase();
  31. // 获取推文作者(用户名)
  32. const usernameElement = tweet.querySelector('a[href*="/"]');
  33. const username = usernameElement ? usernameElement.getAttribute('href').split('/')[1].toLowerCase() : '';
  34.  
  35. // 检查是否需要隐藏
  36. const hideTweet = filterConfig.keywords.some(keyword => text.includes(keyword.toLowerCase())) ||
  37. filterConfig.accounts.includes(username);
  38.  
  39. if (hideTweet) {
  40. tweet.style.cssText = filterConfig.hideStyle;
  41. }
  42. } catch (e) {
  43. console.error('Error processing tweet:', e);
  44. }
  45. });
  46. }
  47.  
  48. // 动态监听页面变化(Twitter/X是动态加载的)
  49. const observer = new MutationObserver((mutations) => {
  50. mutations.forEach(() => {
  51. filterTweets();
  52. });
  53. });
  54.  
  55. // 启动观察器
  56. function startObserver() {
  57. const targetNode = document.body;
  58. if (targetNode) {
  59. observer.observe(targetNode, { childList: true, subtree: true });
  60. filterTweets(); // 初始过滤
  61. } else {
  62. setTimeout(startObserver, 1000); // 如果页面未加载完成,延迟重试
  63. }
  64. }
  65.  
  66. // 初始化
  67. startObserver();
  68.  
  69. // 快捷键开关(按Ctrl+Shift+F切换过滤)
  70. let isFilterEnabled = true;
  71. document.addEventListener('keydown', (e) => {
  72. if (e.ctrlKey && e.shiftKey && e.key === 'F') {
  73. isFilterEnabled = !isFilterEnabled;
  74. if (isFilterEnabled) {
  75. filterTweets();
  76. console.log('Twitter/X Search Filter: Enabled');
  77. } else {
  78. document.querySelectorAll('article[data-testid="tweet"]').forEach(tweet => {
  79. tweet.style.cssText = ''; // 恢复显示
  80. });
  81. console.log('Twitter/X Search Filter: Disabled');
  82. }
  83. }
  84. });
  85.  
  86. })();