-
Notifications
You must be signed in to change notification settings - Fork 1
/
pf_post_autosave.user.js
116 lines (96 loc) · 3.05 KB
/
pf_post_autosave.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// ==UserScript==
// @name ProgrammersForumAutosave
// @namespace http://programmersforum.ru/
// @version 0.10
// @description saves new post text to localStorage and restores it if closed the page without submitting (separate for each thread)
// @author Alex P
// @include *programmersforum.ru/*
// @grant none
// @downloadURL https://github.com/AlexP11223/ProgForumRuUserscripts/raw/master/pf_post_autosave.user.js
// ==/UserScript==
var postautosave_u = new function() {
'use strict';
var self = this;
function isStorageSupported() {
try {
return 'localStorage' in window && window.localStorage !== null;
} catch(e) {
return false;
}
}
function doInit(options) {
var form = $('form[action*="newreply.php"]');
var textarea = form.find('textarea');
var threadIdField = form.find('input[name="t"]');
if (!form.length || !textarea.length || !threadIdField.length) {
return;
}
var threadId = threadIdField.val();
var storageId = 'new_post_thread' + threadId;
var oldText = window.localStorage.getItem(storageId);
if (oldText) {
textarea.val(oldText);
}
var submitted = false;
form.submit(function () {
try {
submitted = true;
if (timer) {
timer = clearTimeout(timer);
}
window.localStorage.removeItem(storageId);
} catch(e) {
console.log(e);
}
});
var timer = null;
function save() {
if (submitted) {
return;
}
var text = textarea.val();
if (text) {
window.localStorage.setItem(storageId, text);
} else {
if (window.localStorage.getItem(storageId)) {
if (!(form.find('textarea').length)) {
return;
}
window.localStorage.removeItem(storageId);
}
}
timer = null;
}
function startSave() {
if (timer == null) {
submitted = false;
timer = setTimeout(save, options.saveDelay);
}
}
textarea.change(startSave);
textarea.on('input', startSave);
textarea.on('blur', startSave);
window.addEventListener("unload", function () {
save();
});
}
this.init = function(options) {
var defaultOptions = {
saveDelay: 1000
};
if (options === undefined) {
options = defaultOptions;
} else {
options = $.extend(defaultOptions, options);
}
if (window.postAutosaveInitialized)
return;
window.postAutosaveInitialized = true;
if (!isStorageSupported())
return;
$(function() {
doInit(options);
});
};
};
postautosave_u.init();