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

bannerbanner/src/ content_script.js
80 lines
2.1 KiB

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