Skip to content

Instantly share code, notes, and snippets.

@biaocy
Last active May 19, 2024 21:20
Show Gist options
  • Save biaocy/e80b83af1c13c9f6bd712efb759822ed to your computer and use it in GitHub Desktop.
Save biaocy/e80b83af1c13c9f6bd712efb759822ed to your computer and use it in GitHub Desktop.
Replace twitter ugly font in Chinese and remove ad tweet!
// ==UserScript==
// @name Twitter related
// @namespace http://tampermonkey.net/
// @version 0.2
// @description Replace twitter ugly font in Chinese and remove ad tweet!
// @author Bill Chan
// @match https://twitter.com/*
// @match https://x.com/*
// @icon
// @grant none
// @updateURL https://gist.githubusercontent.com/biaocy/e80b83af1c13c9f6bd712efb759822ed/raw/twitter-monkey.js
// @downloadURL https://gist.githubusercontent.com/biaocy/e80b83af1c13c9f6bd712efb759822ed/raw/twitter-monkey.js
// ==/UserScript==
(async function() {
'use strict';
function replaceFont() {
var rule = `div[data-testid="tweetText"] > span {
font-family: system-ui !important;
}`;
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.style.cssText) {
styleElement.style.cssText = rule;
} else {
styleElement.appendChild(document.createTextNode(rule));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function removeNodeAfterSecond(node, sec=1) {
await sleep(sec * 1000);
if (node.parentNode) {
node.parentNode.removeChild(node)
console.log('remove ad', node)
}
}
function removeAdTweet() {
// Select the node that will be observed for mutations
//const targetNode = document.querySelector('div[aria-label="Timeline: Your Home Timeline"]')
const targetNode = document.body
// Options for the observer (which mutations to observe)
const config = { attributes: false, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
for (const addedNode of mutation.addedNodes) {
if (addedNode.localName == 'div' && addedNode.dataset.testid == 'cellInnerDiv') {
let isAd = false;
for (const span of addedNode.querySelectorAll('span')) {
if (span.innerHTML.trim() == 'Ad') {
isAd = true;
break
}
}
if (isAd) {
addedNode.style.display = 'none'
console.log('remove ad', addedNode)
//removeNodeAfterSecond(addedNode) // Remove node directly will cause Elon to stop loading tweet
break
}
}
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
return observer;
}
replaceFont();
removeAdTweet();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment