简体   繁体   中英

How can I successfully add a new button to the top bar of Reddit new layout

I'm trying to create a user script to add a new button to the new Reddit design so I can return to the old layout easily. The new button goes somewhere around here.

This is my simple code:

var parent = document.getElementsByClassName('s17th0jh-5 iAfVlC')

var bOld = document.createElement("button");
bOld.innerHTML = "old";
parent[0].appendChild(bOld);

bOld.addEventListener("click", function() {
  var url = document.URL;
  url = url.replace('/www.', '/old.');
  window.location.href = url;
});

The problem is, every time I load or reload the page the new button appears and quickly disappears within a second. How can I fix this?

Can you add your function in a window.load function or something? It sounds like reddit has some javascript which is executing after yours (which has a side effect of deleting your button). If you can get yours to execute after reddit's perhaps it would work?

window.addEventListener('load', function() { /*YOUR CODE*/ });

The problem might be because since reddit is using react , your changes are getting overwritten due to re - rendering. Because after your script executes the component gets re - rendered. But the solution to this problem is using setTimeout .In this, after the component/header is done rendering , your script will then append your button/link

 var parent = document.getElementsByClassName('s17th0jh-5 iAfVlC') var bOld = document.createElement("button"); bOld.innerHTML = "old"; setTimeout(function(){ parent[0].appendChild(bOld); bOld.addEventListener("click", function() { var url = document.URL; url = url.replace('/www.', '/old.'); window.location.href = url; }); },1000) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM