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

bannerbanner/src/ content_script.js
77 lines
2.2 KiB

  1. import browser from 'webextension-polyfill'
  2. import throttle from 'lodash/throttle'
  3. import { onEnabledChange, isEnabled } from './perOrigin'
  4. function hideBanners() {
  5. const revertSteps = []
  6. /* Hide all elements with position:fixed */
  7. const fixedElements = Array.from(document.querySelectorAll('*'))
  8. .filter(el => (
  9. getComputedStyle(el).position === 'fixed'
  10. && el.style.opacity !== '0' // ignore if we already hid this one
  11. ))
  12. fixedElements.forEach(el => {
  13. const originalVisibility = el.style.visibility
  14. const originalOpacity = el.style.opacity
  15. const originalTransition = el.style.transition
  16. el.style.transition = 'opacity 1s'
  17. el.style.opacity = '0'
  18. const hiderTimeoutId = window.setTimeout(() => {
  19. el.style.visibility = 'hidden'
  20. }, 1000)
  21. revertSteps.push(() => {
  22. window.clearTimeout(hiderTimeoutId)
  23. const reverterTimeoutId = window.setTimeout(() => {
  24. el.style.transition = originalTransition
  25. }, 1000)
  26. el.style.visibility = originalVisibility
  27. el.style.opacity = originalOpacity
  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 revertSteps = []
  44. // XXX We read the location only once, but it may be changed by page scripts.
  45. // Fortunately we only need the origin, which should remain the same.
  46. const url = window.location.href
  47. async function run() {
  48. const enabled = await isEnabled(url)
  49. if (enabled && window.scrollY > 20) {
  50. // Hide everything that looks annoying. Remember the steps to revert this.
  51. revertSteps = hideBanners().concat(revertSteps)
  52. } else if (!enabled || window.scrollY <= 0) {
  53. // Unhide everything we have hidden.
  54. revertSteps.forEach(step => step())
  55. revertSteps = []
  56. }
  57. }
  58. window.addEventListener('scroll', throttle(run, 300))
  59. onEnabledChange(url, run)
  60. }
  61. main()