Greasy Fork is available in English.
Add "Translate tweet with DeepL" button
当前为
// ==UserScript==
// @name Magic DeepL Twitter translation
// @namespace https://github.com/magicoflolis
// @version 0.4
// @description Add "Translate tweet with DeepL" button
// @author Magic of Lolis
// @match https://twitter.com/*
// @grant none
// @require https://code.jquery.com/jquery-3.5.1.min.js
// ==/UserScript==
( () => {
'use strict';
let injected = null,
injectInterval = null,
waitForHeadNodeInterval = null;
function isHTML(str) {
let doc = new DOMParser().parseFromString(str, "text/html");
return Array.from(doc.body.childNodes).some(node => node.nodeType === 1);
}
function injectDeeplTranslationButton() {
let start = () => {
let translateButton = $("div[lang]").eq(0).siblings().eq(0).children("span"),
deeplbtn = $("div[lang]").eq(0).siblings().eq(1).children("span"),
deepbtn = () => {
// Get the tweet content
let tweetContainer = translateButton.parent().siblings(),
tweetLang = tweetContainer.attr("lang"),
tweetContent = "",
deeplButton = translateButton.parent().clone().appendTo(translateButton.parent().parent());
tweetContainer.children("span").each((index,item) => {
let tweetPart = $(item).html().trim();
if(tweetPart && tweetPart != "" && !isHTML(tweetPart)) {
tweetContent += " " + tweetPart;
}
});
deeplButton.children("span").html("Translate Tweet with DeepL");
deeplButton.hover(function() {
$(this).css("text-decoration", "underline");
}, function() {
$(this).css("text-decoration", "none");
});
deeplButton.on("click", () => {
window.open(`https://www.deepl.com/translator#${tweetLang}/en/${tweetContent}`,'_blank');
})
}
injected = true;
clearInterval(injectInterval);
injectInterval = null;
(deeplbtn.length != 1 && translateButton.length > 0) ? deepbtn() : false;
};
injected ?? start();
}
function addObserverIfHeadNodeAvailable() {
const target = $("head > title")[0],
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
observer = new MutationObserver((mutations) => {
mutations.forEach( () => {
function re() {
injected = null;
injectInterval = setInterval(injectDeeplTranslationButton, 100);
}
injectInterval ?? re();
});
});
if(!target) {
return;
}
clearInterval(waitForHeadNodeInterval);
observer.observe(target, { subtree: true, characterData: true, childList: true });
}
waitForHeadNodeInterval = setInterval(addObserverIfHeadNodeAvailable, 100);
})();