Skip to content

Instantly share code, notes, and snippets.

@LenAnderson
Last active January 21, 2022 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenAnderson/cd84ac6f6329fd111b43f0a962a7364d to your computer and use it in GitHub Desktop.
Save LenAnderson/cd84ac6f6329fd111b43f0a962a7364d to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Reddit - Header Image
// @namespace http://tampermonkey.net/
// @version 0.2
// @description try to take over the world!
// @author You
// @match https://www.reddit.com/r/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=reddit.com
// @connect old.reddit.com
// @connect b.thumbs.redditmedia.com
// @connect a.thumbs.redditmedia.com
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
const setHeader = (url)=>{
const header = document.querySelector('#header');
header.style.height = '100px';
header.style.backgroundImage = url.map(it=>`url("${it}")`).join(',');
header.style.backgroundSize = 'auto 100%';
const bottomLeft = document.querySelector('#header-bottom-left');
bottomLeft.style.marginTop = '36px';
bottomLeft.style.backgroundColor = 'rgba(255, 255, 255, 0.25)';
};
const run = async()=>{
const about = await (await fetch(`${location.href.replace(/^(https:\/\/www\.reddit\.com\/r\/[^\/]+\/).*$/, '$1')}about.json`)).json();
let bgImg = about.data.banner_img;
if (bgImg) {
setHeader([bgImg]);
} else {
console.log('checking stylesheet: ', `https://old.${location.href.replace(/^https:\/\/www\.(reddit\.com\/r\/[^\/]+\/).*$/, '$1')}stylesheet`);
GM_xmlhttpRequest({
method: 'GET',
cookie: 'over18=1',
url: `https://old.${location.href.replace(/^https:\/\/www\.(reddit\.com\/r\/[^\/]+\/).*$/, '$1')}stylesheet`,
anonymous: true,
onload: (data)=>{
const style = document.createElement('style');
style.innerHTML = data.responseText;
console.log(data.responseText);
const html = document.createElement('div');
const shadow = html.attachShadow({mode:'closed'});
shadow.innerHTML = document.body.innerHTML;
Array.from(shadow.querySelectorAll('script')).forEach(it=>it.remove());
shadow.append(style);
document.body.append(html);
console.log('#header', getComputedStyle(shadow.querySelector('#header')).backgroundImage);
console.log('#header-bottom-left', getComputedStyle(shadow.querySelector('#header-bottom-left')).backgroundImage);
bgImg = getComputedStyle(shadow.querySelector('#header')).backgroundImage;
if (bgImg.search(/^.*url\(["']?([^"'\)]+)["']?\).*$/) == -1) {
bgImg = getComputedStyle(shadow.querySelector('#header-bottom-left')).backgroundImage;
}
if (bgImg.search(/^.*url\(["']?([^"'\)]+)["']?\).*$/) > -1) {
bgImg = bgImg.split(',').map(it=>it.replace(/^.*url\(["']?([^"'\)]+)["']?\).*$/, '$1'));
} else {
bgImg = false;
}
html.remove();
if (bgImg) {
setHeader(bgImg);
}
}
});
}
};
run();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment