Protect Textarea

Confirm before closing a web page with modified textareas

  1. // ==UserScript==
  2. // @name Protect Textarea
  3. // @namespace http://www.arantius.com/
  4. // @description Confirm before closing a web page with modified textareas
  5. // @include *
  6. // @exclude http*://*mail.google.com/*
  7. // @version 0.0.1.20190827001948
  8. // ==/UserScript==
  9.  
  10. // based on code by Anthony Lieuallen
  11. // and included here with his gracious permission
  12. // http://www.arantius.com/article/arantius/protect+textarea/
  13.  
  14. //indicator to skip handler because the unload is caused by form submission
  15. var _pt_skip=false;
  16. var real_submit = null;
  17.  
  18. //find all textarea elements and record their original value
  19. var els=document.evaluate('//textarea',
  20. document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  21. for (var el=null, i=0; el=els.snapshotItem(i); i++) {
  22. var real_el = el.wrappedJSObject || el;
  23. real_el._pt_orig_value=el.value;
  24. }
  25.  
  26. //if i>0 we found textareas, so do the rest
  27. if (i == 0) { return; }
  28. //this function handles the case where we are submitting the form,
  29. //in this case, we do not want to bother the user about losing data
  30. var handleSubmit = function() {
  31. _pt_skip=true;
  32. return real_submit();
  33. }
  34. //this function will handle the event when the page is unloaded and
  35. //check to see if any textareas have been modified
  36. var handleUnload = function() {
  37. if (_pt_skip) { return; }
  38. var els=document.getElementsByTagName('textarea');
  39. for (var el=null, i=0; el=els[i]; i++) {
  40. var real_el = el.wrappedJSObject || el;
  41. if (real_el._pt_orig_value!=el.value) {
  42. return 'You have modified a textarea, and have not ' +
  43. 'submitted the form.';
  44. }
  45. }
  46. }
  47. // trap form submit to set flag
  48. real_submit = HTMLFormElement.prototype.submit;
  49. HTMLFormElement.prototype.submit = handleSubmit;
  50. window.addEventListener('submit', handleSubmit, true);
  51.  
  52. // trap unload to check for unmodified textareas
  53. unsafeWindow.onbeforeunload = handleUnload;