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

bannerbanner/src/ content_script.js
83 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 originalVisibility = el.style.visibility
  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.visibility = 'hidden'
  18. }, 1000)
  19. revertSteps.push(() => {
  20. window.clearTimeout(hiderTimeoutId)
  21. const reverterTimeoutId = window.setTimeout(() => {
  22. el.style.transition = originalTransition
  23. }, 1000)
  24. el.style.visibility = originalVisibility
  25. el.style.opacity = originalOpacity
  26. })
  27. })
  28. /* Stop position:sticky elements from sticking. */
  29. const stickyElements = Array.from(document.querySelectorAll('*'))
  30. .filter(el => getComputedStyle(el).position === 'sticky')
  31. stickyElements.forEach(el => {
  32. const originalPosition = el.style.position
  33. el.style.position = 'relative'
  34. revertSteps.push(() => {
  35. el.style.position = originalPosition
  36. })
  37. })
  38. return revertSteps
  39. }
  40. function main() {
  41. let state = 'off'
  42. let revertSteps = []
  43. let lastRun
  44. function onScroll(event) {
  45. let action
  46. if (window.scrollY > 20 &&
  47. (state === 'off' || (state === 'on' && event.timeStamp - lastRun > 1000))
  48. ) {
  49. lastRun = event.timeStamp
  50. state = 'starting'
  51. action = () => {
  52. revertSteps = hideBanners().concat(revertSteps)
  53. state = 'on'
  54. }
  55. } else if (window.scrollY <= 0 && state === 'on') {
  56. state = 'stopping'
  57. action = () => {
  58. revertSteps.forEach(step => step())
  59. revertSteps = []
  60. state = 'off'
  61. }
  62. }
  63. if (action) {
  64. window.requestAnimationFrame(action)
  65. }
  66. }
  67. window.addEventListener('scroll', onScroll)
  68. }
  69. main()