Browser extension to hide view-reducing screen junk from websites.

bannerbanner/src/ content_script.js
85 lines
2.1 KiB

  1. import browser from 'webextension-polyfill'
  2. function hideBanners() {
  3. const revertSteps = []
  4. /* Hide all elements with position:fixed */
  5. const fixedElements = Array.from(document.querySelectorAll('*'))
  6. .filter(el => (
  7. getComputedStyle(el).position === 'fixed'
  8. && el.style.opacity !== '0' // ignore if we already hid this one
  9. ))
  10. fixedElements.forEach(el => {
  11. const originalDisplay = el.style.display
  12. const originalOpacity = el.style.opacity
  13. const originalTransition = el.style.transition
  14. el.style.transition = 'opacity 1s'
  15. el.style.opacity = '0'
  16. const hiderTimeoutId = window.setTimeout(() => {
  17. el.style.display = 'none'
  18. }, 1000)
  19. revertSteps.push(() => {
  20. window.clearTimeout(hiderTimeoutId)
  21. const reverterTimeoutId = window.setTimeout(() => {
  22. el.style.transition = originalTransition
  23. }, 1000)
  24. el.style.display = originalDisplay
  25. window.setTimeout(() => {
  26. el.style.opacity = originalOpacity
  27. })
  28. })
  29. })
  30. /* Stop position:sticky elements from sticking. */
  31. const stickyElements = Array.from(document.querySelectorAll('*'))
  32. .filter(el => getComputedStyle(el).position === 'sticky')
  33. stickyElements.forEach(el => {
  34. const originalPosition = el.style.position
  35. el.style.position = 'relative'
  36. revertSteps.push(() => {
  37. el.style.position = originalPosition
  38. })
  39. })
  40. return revertSteps
  41. }
  42. function main() {
  43. let state = 'off'
  44. let revertSteps = []
  45. let lastRun
  46. function onScroll(event) {
  47. let action
  48. if (window.scrollY > 20 &&
  49. (state === 'off' || (state === 'on' && event.timeStamp - lastRun > 1000))
  50. ) {
  51. lastRun = event.timeStamp
  52. state = 'starting'
  53. action = () => {
  54. revertSteps = hideBanners().concat(revertSteps)
  55. state = 'on'
  56. }
  57. } else if (window.scrollY <= 0 && state === 'on') {
  58. state = 'stopping'
  59. action = () => {
  60. revertSteps.forEach(step => step())
  61. revertSteps = []
  62. state = 'off'
  63. }
  64. }
  65. if (action) {
  66. window.requestAnimationFrame(action)
  67. }
  68. }
  69. window.addEventListener('scroll', onScroll)
  70. }
  71. main()