Protect Textarea

By arantius Last update Oct 6, 2005 — Installed 1,482 times. Daily Installs: 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0
// ==UserScript==
// @name          Protect Textarea
// @namespace     http://www.arantius.com/article/arantius/protect+textarea/
// @description	  Protect from closing or navigating away from a web page with changed textareas.
// @include       *
// @exclude       http*://gmail.google.com/*
// @exclude       http*://mail.google.com/*
// ==/UserScript==

//
// Originally written by Anthony Lieuallen of http://www.arantius.com/
// Licensed for unlimited modification and redistribution as long as
// this notice is kept intact.
//
// If possible, please contact me regarding new features, bugfixes
// or changes that I could integrate into the existing code instead of
// creating a different script.  Thank you
//

//
// TODO:
//  - Figure out why we can't use addEvent Listener
//  - Perhaps a bit more info in the confirm box.  Perhaps information 
//     about the page that caused it in case of closing a browser with
//     many open tabs.
//

//indicator to skip handler because the unload is caused by form submission
window._pt_skip=false;

//find all textarea elements and record their original value
var els=document.evaluate('//textarea', 
	document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var el=null, i=0; el=els.snapshotItem(i); i++) {
	el._pt_orig_value=el.value;
}

//if i>0 we found textareas, so do the rest
if (i>0) {
	//this function handles the case where we are submitting the form,
	//in this case, we do not want to bother the user about losing data
	var handleSubmit = function() {
		window._pt_skip=true;
	}

	//attach handler function to forms
	var els=document.evaluate('//form', 
		document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
	for (var el=null, i=0; el=els.snapshotItem(i); i++) {
		el.addEventListener('submit', handleSubmit, true);
	}

	//this function will handle the event when the page is unloaded and
	//check to see if any textareas have been modified
	var handleUnload = function() {
		if (true==window._pt_skip) return;
		var els=document.evaluate('//textarea', 
			document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		for (var el=null, i=0; el=els.snapshotItem(i); i++) {
			if (el._pt_orig_value!=el.value) {
				return 'You have modified a textarea, and have not submitted the form.';
			}
		}
		return;
	}

	//window.addEventListener('beforeunload', handleUnload, true);
	//how come that ^^ doesn't work and we have to do this vv ?
	window.onbeforeunload=handleUnload;
}