Guest User

Untitled

a guest
Sep 24th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. addEventListener('fetch', event => {
  2. event.respondWith(fetchAndApply(event.request))
  3. })
  4.  
  5. /**
  6. * If the browser is requesting an image and
  7. * the referer does not match your host
  8. * we redirect the request to your page
  9. */
  10. async function fetchAndApply(request) {
  11. // Fetch the response.
  12. let response = await fetch(request)
  13.  
  14. // If it's an image, engage hotlink protection based on the
  15. // Referer header.
  16. let referer = request.headers.get('Referer')
  17. let contentType = response.headers.get('Content-Type') || ''
  18.  
  19. let whitelist = [ 'domain1.com', 'domain2.com' ];
  20.  
  21. if (referer && contentType.startsWith('image/')) {
  22. // It's an image and there's a Referer. Verify that the
  23. // hostnames match.
  24. if (
  25. new URL(referer).hostname !== new URL(request.url).hostname
  26. && !whitelist.includes(new URL(referer).hostname)
  27. ) {
  28. // Hosts don't match. This is a hotlink. Redirect the
  29. // user to our homepage.
  30. return new Response('', {
  31. status: 302,
  32. headers: {
  33. 'Location': '/'
  34. }
  35. })
  36. }
  37. }
  38.  
  39. // Everything is fine, return the response normally.
  40. return response
  41. }
Add Comment
Please, Sign In to add comment