Backspace to Go Back

Go back to the previous page using the backspace key

  1. // ==UserScript==
  2. // @name Backspace to Go Back
  3. // @namespace gobackxFIRKx
  4. // @description Go back to the previous page using the backspace key
  5. // @version 1.03
  6. // @author xFIRKx
  7. // @match *://*/*
  8. // @grant none
  9. // @homepageURL https://greasyfork.org/it/scripts/495770-backspace-to-go-back
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. function handleKeydown(event) {
  16. // Check if the pressed key is the backspace key
  17. if ((event.key === 'Backspace' || event.keyCode === 8) && !event.defaultPrevented) {
  18. // Check if the focus is not on an editable element
  19. const activeElement = document.activeElement;
  20. const isInput = activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA' || activeElement.isContentEditable;
  21. const isReadOnly = activeElement.readOnly || activeElement.disabled;
  22.  
  23. if (!isInput || isReadOnly) {
  24. event.preventDefault(); // Prevent the default action
  25. window.history.back(); // Go back to the previous page
  26. }
  27. }
  28. }
  29.  
  30. // Add event listener for keydown events
  31. document.addEventListener('keydown', handleKeydown, true); // Use capture mode to ensure the event is caught early
  32.  
  33. // Use MutationObserver to handle dynamic content changes
  34. const observer = new MutationObserver(() => {
  35. // Reattach the event listener if necessary
  36. document.removeEventListener('keydown', handleKeydown, true);
  37. document.addEventListener('keydown', handleKeydown, true);
  38. });
  39.  
  40. // Observe changes in the document body
  41. observer.observe(document.body, { childList: true, subtree: true });
  42.  
  43. // Additional observer for YouTube's specific dynamic content
  44. if (window.location.hostname.includes('youtube.com')) {
  45. const ytObserver = new MutationObserver(() => {
  46. const contentElement = document.querySelector('ytd-app');
  47. if (contentElement) {
  48. ytObserver.observe(contentElement, { childList: true, subtree: true });
  49. }
  50. });
  51.  
  52. ytObserver.observe(document.body, { childList: true, subtree: true });
  53. }
  54. })();