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

bannerbanner/src/ content_script.js
78 lines
1.9 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 => getComputedStyle(el).position === 'fixed')
  7. fixedElements.forEach(el => {
  8. const originalDisplay = el.style.display
  9. const originalOpacity = el.style.opacity
  10. const originalTransition = el.style.transition
  11. el.style.transition = 'opacity 1s'
  12. el.style.opacity = '0'
  13. const hiderTimeoutId = window.setTimeout(() => {
  14. el.style.display = 'none'
  15. }, 1000)
  16. revertSteps.push(() => {
  17. window.clearTimeout(hiderTimeoutId)
  18. const reverterTimeoutId = window.setTimeout(() => {
  19. el.style.transition = originalTransition
  20. }, 1000)
  21. el.style.display = originalDisplay
  22. window.setTimeout(() => {
  23. el.style.opacity = originalOpacity
  24. })
  25. })
  26. })
  27. /* Stop position:sticky elements from sticking. */
  28. const stickyElements = Array.from(document.querySelectorAll('*'))
  29. .filter(el => getComputedStyle(el).position === 'sticky')
  30. stickyElements.forEach(el => {
  31. const originalPosition = el.style.position
  32. el.style.position = 'relative'
  33. revertSteps.push(() => {
  34. el.style.position = originalPosition
  35. })
  36. })
  37. return revertSteps
  38. }
  39. function main() {
  40. let state = 'off'
  41. let revertSteps = []
  42. function onScroll() {
  43. let action
  44. if (window.scrollY > 20 && state === 'off') {
  45. state = 'starting'
  46. action = () => {
  47. revertSteps = revertSteps.concat(hideBanners())
  48. state = 'on'
  49. }
  50. } else if (window.scrollY <= 0 && state === 'on') {
  51. state = 'stopping'
  52. action = () => {
  53. revertSteps.forEach(step => step())
  54. revertSteps = []
  55. state = 'off'
  56. }
  57. }
  58. if (action) {
  59. window.requestAnimationFrame(action)
  60. }
  61. }
  62. window.addEventListener('scroll', onScroll)
  63. }
  64. main()