You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

routePrefixHandle.tsx 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use client'
  2. import { basePath } from '@/utils/var'
  3. import { useEffect } from 'react'
  4. import { usePathname } from 'next/navigation'
  5. export default function RoutePrefixHandle() {
  6. const pathname = usePathname()
  7. const handleRouteChange = () => {
  8. const addPrefixToImg = (e: HTMLImageElement) => {
  9. const url = new URL(e.src)
  10. const prefix = url.pathname.substr(0, basePath.length)
  11. if (prefix !== basePath) {
  12. url.pathname = basePath + url.pathname
  13. e.src = url.toString()
  14. }
  15. }
  16. // create an observer instance
  17. const observer = new MutationObserver((mutationsList) => {
  18. for (const mutation of mutationsList) {
  19. if (mutation.type === 'childList') {
  20. // listen for newly added img tags
  21. mutation.addedNodes.forEach((node) => {
  22. if (((node as HTMLElement).tagName) === 'IMG')
  23. addPrefixToImg(node as HTMLImageElement)
  24. })
  25. }
  26. else if (mutation.type === 'attributes' && (mutation.target as HTMLElement).tagName === 'IMG') {
  27. // if the src of an existing img tag changes, update the prefix
  28. if (mutation.attributeName === 'src')
  29. addPrefixToImg(mutation.target as HTMLImageElement)
  30. }
  31. }
  32. })
  33. // configure observation options
  34. const config = {
  35. childList: true,
  36. attributes: true,
  37. subtree: true,
  38. attributeFilter: ['src'],
  39. }
  40. observer.observe(document.body, config)
  41. }
  42. useEffect(() => {
  43. if (basePath)
  44. handleRouteChange()
  45. }, [pathname])
  46. return null
  47. }