Greasy Fork is available in English.

X (Twitter) Bookmark Scroll Position Keeper

Fixes automatic scroll to top after clicking on a bookmarked post in X (formerly Twitter) Bookmarks page

  1. // ==UserScript==
  2. // @name X (Twitter) Bookmark Scroll Position Keeper
  3. // @name:zh-CN X (推特) 书签滚动位置保持器
  4. // @namespace http://tampermonkey.net/
  5. // @author Roy WU
  6. // @version 0.4
  7. // @description Fixes automatic scroll to top after clicking on a bookmarked post in X (formerly Twitter) Bookmarks page
  8. // @description:zh-CN 修复X(前Twitter)书签页面点击书签后自动滚动到顶部的问题,保持滚动位置
  9. // @match https://x.com/*
  10. // @match https://twitter.com/*
  11. // @grant none
  12. // @license MIT
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let posY = 0;
  18. let isBookmarksPage = false;
  19. // 检查当前是否在书签页面
  20. function checkIfBookmarksPage() {
  21. isBookmarksPage = window.location.pathname.includes('/i/bookmarks');
  22. console.log('Is bookmarks page:', isBookmarksPage);
  23. }
  24. // 监听滚动事件
  25. function handleScroll() {
  26. if (!isBookmarksPage) return;
  27. const scrollPosition = window.scrollY;
  28. if (window.scrollY === 0) {
  29. console.log("back to zero!");
  30. window.scrollTo(0, posY);
  31. } else {
  32. posY = scrollPosition;
  33. }
  34. console.log(scrollPosition);
  35. }
  36. // 初始化
  37. function init() {
  38. checkIfBookmarksPage();
  39. window.addEventListener('scroll', handleScroll);
  40. }
  41. // 监听 URL 变化
  42. function observeUrlChanges() {
  43. const observer = new MutationObserver(function(mutations) {
  44. mutations.forEach(function(mutation) {
  45. if (location.href !== mutation._oldURL) {
  46. checkIfBookmarksPage();
  47. }
  48. });
  49. });
  50. observer.observe(document.body, {
  51. childList: true,
  52. subtree: true
  53. });
  54. }
  55. // 启动监听
  56. init();
  57. observeUrlChanges();
  58. // 使用 history API 的监听作为后备方案
  59. window.addEventListener('popstate', checkIfBookmarksPage);
  60. window.addEventListener('pushstate', checkIfBookmarksPage);
  61. window.addEventListener('replacestate', checkIfBookmarksPage);
  62. })();