-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebEraser.user.js
2255 lines (2001 loc) · 94.3 KB
/
WebEraser.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name WebEraser
// @version 1.7.5
// @updateURL https://openuserjs.org/meta/slow!/WebEraser.meta.js
// @downloadURL https://openuserjs.org/install/slow!/WebEraser.user.js
// @namespace sfswe
// @description Erase parts of any webpage --annoyances, logos, ads, images, etc., permanently with just, Ctrl + Left-Click.
// @license GPL-3.0-only
// @copyright 2018, TerryCross (https://github.com/TerryCross)
// @include *
// @require https://code.jquery.com/jquery-3.2.1.js
// @require https://code.jquery.com/ui/1.12.1/jquery-ui.js
// @require https://raw.githubusercontent.com/TerryCross/code/master/sfs-utils-0.1.6.js
// @run-at document-start
// @icon https://raw.githubusercontent.com/TerryCross/imgstore/master/WebEraserIcon.gif
// @author Sloane Fox
// @grant GM_registerMenuCommand
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_xmlhttpRequest
// @grant GM_getResourceURL
// @grant GM_addStyle
// @grant GM.registerMenuCommand
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.listValues
// @grant GM.xmlHttpRequest
// @grant GM.getResourceUrl
// ==/UserScript==
var gobj, preferences;
main();
async function main() {
[gobj, preferences] = initGlobalObjects();
profileTimer("w/e start");
await listenForPageLoad();
}
async function listenForPageLoad() {
if(gobj.iframe)
installEventHandlers();
else {
await userscriptManagerInit();
profileTimer("preMain-half");
await loadResources();
}
}
async function loadResources() { //attempt to get in at document-start, either preload of js or of images slows page load too much. However, eval of js files will not help.
await getUserPreferences();
await attachToPage();
const haveNothingToErase = (gobj.elems_to_be_erased == "" && !gobj.nonGMmode);
if(haveNothingToErase)
console.log("WebEraser, nothing to erase.");
else
await loadAndListen();
}
async function loadAndListen() {
await loadLazyResources(); ///////////// loadLazyResources loads @require files.
const domIsLoaded = (/^complete/.test(document.readyState));
if(domIsLoaded)
performErasures();
else
document.addEventListener("readystatechange", performErasures()); //main(); addEventListener("load", main.bind(environ)) ; // In a normal GM environment, main will be called at docready.
}
async function attachToPage() {
profileTimer("preMain()-inited globs");
installEventHandlers();
await registerCommands();
}
async function getUserPreferences() {
preferences.page_erasedElems = (await getValue(gobj.webpage+":erasedElems","")).trim();
preferences.site_erasedElems = (await getValue(gobj.website+":erasedElems","")).trim();
preferences.config = await getValue("config",{keepLayout:"checked", monitor:{}});
if (!preferences.config.monitor) preferences.config.monitor = {};
gobj.elems_to_be_erased = getErasedElemsCmd();
}
async function performErasures() { try{
profileTimer("main()-start");
//console.log("w/e main GM:", typeof GM, "readyState", document.readyState,"body:", document.body,"iframe", gobj.iframe,"jQuery:", window.jQuery&&window.jQuery.fn.jquery,"$", window.$);
inner_eraseElements("init");
const nerased = $(".Web-Eraser-ed").length, delay = 5000+300*(2+nerased), forErasure = getErasedElemsCmd("count");
tryAgain(delay, nerased); // Try again to look for elements to erase after for page to complete loading.
profileTimer("main()-end");
} catch(e){console.error("WebEraser main(), error:", e);}} //main()
function tryAgain(delay, nerased) {
setTimeout( x=> {
//console.log("End of", delay,"delay, checking for inner_eraseElements", preferences.page_erasedElems,"or", preferences.site_erasedElems);
performErasuresPhaseTwo(delay);
installEventHandlers("phase2"); // for iframes that delay in loading.
profileTimer("end delayed phase2");
}, delay);
}
function performErasuresPhaseTwo(delay) {
profileTimer("start of phase 2 "+delay+"ms later ");
const haveElsToErase = (preferences.page_erasedElems || preferences.site_erasedElems);
if(haveElsToErase)
inner_eraseElements("delay");
else if ($(".Web-Eraser-ed").length == 0 && gobj.elems_to_be_erased)
console.info("WebEraser message: no match for any selectors:", getErasedElemsCmd(),"\nWebpage:", gobj.webpage);
}
async function loadLazyResources() { try{ // called from main and form click handler, completes main when have els to erase.
if(loadLazyResources.done) return; loadLazyResources.done = true;
profileTimer("loadLazyResources()-start");
insertPrototypes();
await dynamicLoadRequires(); // sets log()
await init_async_globs(); // depends on load of js polyfill file on FF for 'GM.' funcs.
register_jQandCmds();
} catch(e){console.error("WebEraser loadLazyResources(), error:", e);}} //loadLazyResources()
function register_jQandCmds(){
registerCommands();
ensure_jquery_extended(); // may get clobbered by other script loading jQ.
addStyle();
setTimeout(reattachTornCurtains, 3000);
gobj.sel_matching_els = $();
profileTimer("loadLazyResources()-end");
}
function addStyle() {
GM_addStyle( jqueryui_dialog_css()
+".sfswe-transparentborder { border-color:transparent !important;border-width:"+gobj.border_width+"px !important;border-style:double !important; } "
+".sfswe-redborder { border-color:red !important; border-width:"+gobj.border_width+"px !important;border-style:double !important; } "
+"img.WebEraserCurtain { display: block !important; color:#fff !important; }"
+`.CurtainRod {
background-color: #bbb; background-image: linear-gradient(90deg, rgba(255, 255, 255,.07) 50%, transparent 50%), linear-gradient(90deg, rgba(255, 255, 255,.13) 50%, transparent 50%), linear-gradient(90deg, transparent 50%, rgba(255, 255, 255,.17) 50%), linear-gradient(90deg, transparent 50%, rgba(255, 255, 255,.19) 50%); background-size: 13px, 19px, 17px, 15px; }` +".ui-dialog-buttonpane button {color:black !important;}" + 'img[src*="blob:"] { display:block !important; }');
}
async function handleClick(e, click_from_nested_iframe) {
//console.log("handleClick", e, click_from_nested_iframe);
const itsaCtrlClick = (e.ctrlKey && ! e.shiftKey && !e.altKey &&! e.metaKey && e.type == "mousedown");
if (itsaCtrlClick || click_from_nested_iframe) {
prevDef(e);
if(!gobj.iframe) await loadLazyResources();
console.log("ctrl-CLICKed on element:", e.target,"Event:", e);
processClickTarget(e, click_from_nested_iframe);
}
}
function processClickTarget(e, click_from_nested_iframe) {
console.log("processClickTarget");
const target = e.target, related = e.explicitOriginalTarget||e.relatedTarget;
if(/body/i.test(e.target.tagName) && related)
target = related;
userIOtoEraseElement(target, e, click_from_nested_iframe);
}
function userIOtoEraseElement(target, e, click_from_nested_iframe) { try { //called from event handler in page & iframe, and pseudo called from click within iframe.
halter(); // to handle an unload
const frameEl = target.ownerDocument.defaultView.frameElement;
if(frameEl)
target = frameEl;
if(!postUpTheMsg(target, click_from_nested_iframe))
respondToClickTargetType(target, e);
} catch(e) { console.log("W/e Click handling error:", e,"\nLineNumber:"+(e.lineNumber),"Stack:", e.stack); unhalt(); }} //handleClick()
function postUpTheMsg(target, click_from_nested_iframe) {
if(click_from_nested_iframe)
return; // pseudo call from postMessage.
const seltext_len = window.getSelection().toString().length;
return sendToIframeParent(target, seltext_len);
}
function sendToIframeParent(target, seltext_len){
if (seltext_len != 0) {
unhalt();
return true;
}
if (target.blur)
target.blur();
if (gobj.iframe) {
window.parent.postMessage( { type:"sfswe-iframe-click", code:0, src:location.toString() },"*"); // msg, origin makes pseudo call back here.
unhalt();
return true;
}
}
function respondToClickTargetType(target, e){
while (/HTMLUnknownElement/.test(target.toString()))
target = target.parentNode; //Avoid non HTML tags.
eraseTargetElement(target, e);
if(!halter.dialog)
unhalt();
}
function eraseTargetElement(target, e){
console.log("eraseTargetElement");
if(!gobj.tempMode)
askUserToConfirm(target, e);
else
doTempErasure(target);
}
function askUserToConfirm(target, e) {
if ($(target).is(".WebEraserCurtain") && !gobj.tempMode)
confirmUserFullErasure(target, e);
else if (!gobj.tempMode)
if(!bodyClick(target, e))
confirmUserErasure(target);
}
function confirmUserFullErasure(target, e) {
if (e.button == 0) {
const reply = confirm("This will completely erase selected item, continue? \nOn any revisit to webpage you can check in the console for such erasures.");
if (reply) openCurtains("zap", $(target).siblings("img").addBack());
} else
erasurePreferences();
}
function confirmUserErasure(target) {
halter.dialog = true;
inner_eraseElements();
const prom = checkIfPermanentRemoval(target);
prom.then(respondToUserRequest);
prom.catch(function (a){ unhalt();halter.dialog = false;});
}
function respondToUserRequest(confirm_val){ // then takes a function with 2 params, the arg of resolve func call and of reject.
const [permrm, item_sel] = confirm_val;
halter.dialog = false;
unhalt();
if (permrm == Infinity) // sprompt returns Infinity for when extra button (3rd) is clicked. temp-mode delete
startTempMode(item_sel);
if (permrm != false)
inner_eraseElements("click"); //undefined==>escape (cancel)
};
function bodyClick(target, e) {
if ($("body").is(target)) {
console.log("Click was on element,", target,"Event:", e);
if (confirm("WebEraser. You clicked on the main body of the webpage. The body however, is not removable by ctrl-click, try ctrl-clicking on an image or other item on the webpage. Hit 'OK' to open erasure window."))
erasurePreferences();
unhalt();
return true;
}
}
function startTempMode(item_sel) {
gobj.tempMode = true;
alert("\tYou have entered Temporary-Deletion mode.\n\tCtrl-click will now merely remove elements temporarily.\n\nEsc to undo deletions. Reload to revert. Element deleted.");
doTempErasure(item_sel);
escapeCatch(undoDelete,"perm");
}
function doTempErasure(target) {
const t = $(target);
if( ! t.is("body")) {
gobj.last_ones_deleted.push(t);
t.replaceWith("<placeholder delcnt = "+(++gobj.delcnt)+">");
console.info("Temp-mode deleting:", t, t.text());
}
}
function undoDelete() {
if(gobj.delcnt == 0) return;
const L = gobj.last_ones_deleted.pop(), p = $("placeholder[delcnt = "+gobj.delcnt--+"]");
p.replaceWith(L);
console.log("replaced holder with new", L[0]);
L[0].scrollIntoView();
}
function halter() {
window.addEventListener("beforeunload", handlehalt);
}
function handlehalt(event) {
event.returnValue = "a message to stay";
return event.returnValue;
};
function unhalt(){
window.removeEventListener("beforeunload", handlehalt, false);
}
function prehitch(target) { // hitch up hierarchy if click is on element that cannot be red-bordered.
const svg = target.closest("svg"); // DOM method dom-Elem.closest("sel1, sel2, ..."). Also method matches("sels");
if(svg) target = svg;
return target;
}
function checkIfPermanentRemoval(target) { // called from click handler & eraseIframe.
var sconfirm_promise, checkif_resolve, checkif_reject;
const checkif_promise = new Promise((resolve, reject) => { // checkif_promise is returned by this function, checkIfPermanentRemoval().
checkif_resolve = resolve; checkif_reject = reject;
sconfirm_promise = openErasureConfirmation(target);
});//new Promise()
close_of_prompt(sconfirm_promise, checkif_resolve, checkif_reject);
return checkif_promise;
}
function close_of_prompt(sconfirm_promise, checkif_resolve, checkif_reject) {
sconfirm_promise.catch(function(reply){
hlightAndsetsel(0,"off","restore");
checkif_reject("caught");
});
sconfirm_promise.then(handleUserReply.bind(null, {sconfirm_promise, checkif_resolve, checkif_reject}));
}
function handleUserReply(bpkt, reply){
const {sconfirm_promise, checkif_resolve, checkif_reject} = bpkt;
$(document).off('keypress');
$(":data(pewiden-trace)").data("pewiden-trace",""); // remove trace
const complete_rm_ticked = $("#sfswe-checkbox6:checked").length != 0;
const webpage_only_ticked = $("#sfswe-checkbox7:checked").length != 0;
const temp_del_mode_ticked = $("#sfswe-checkbox10:checked").length != 0;
const reply_sel = finishedConfirmation(reply, temp_del_mode_ticked, checkif_resolve);
if(reply_sel !== false){
sconfirm_promise.data = [reply_sel, complete_rm_ticked]; // use ES6 await?
registerSelectorForErasure(reply_sel, checkif_reject, webpage_only_ticked, complete_rm_ticked, checkif_resolve);
}
};
function finishedConfirmation(reply, temp_del_mode_ticked, checkif_resolve, reply_sel){
if( temp_del_mode_ticked && reply) {
hlightAndsetsel(0,"off","restore");
checkif_resolve([Infinity, $("#sfswe-seledip").val().trim()]); // Infinity means 3rd button which was for gobj.tempMode.
return false;
}
if(reply != false)
reply_sel = $("#sfswe-seledip").val().trim();
if(reply!=true) {
hlightAndsetsel(0,"off","restore");
checkif_resolve([reply, reply_sel]);
return false;
};
return reply_sel;
}
function registerSelectorForErasure(reply_sel, checkif_reject, webpage_only, complete_rm, checkif_resolve){
if (reply_sel) {
const ancErased = $(reply_sel).closest(".Web-Eraser-ed"); //.closest, includes current.
if(!checkSelectorBadAncestry(reply_sel, ancErased, checkif_reject))
updateErasedElementsLists(webpage_only, reply_sel, complete_rm, checkif_resolve, checkif_reject);
} else noSelector(checkif_reject);
}
function noSelector(checkif_reject){
hlightAndsetsel(0,"off","restore");
checkif_reject("empty");
}
function checkSelectorBadAncestry(reply_sel, ancErased, checkif_reject){
if (erasedElementsListCmd("isthere?", reply_sel) ||
(ancErased.length && getErasedElemsCmd("match el", ancErased))){
alert("Already attempting erasure of the element specified or parent, if not being erased properly try "+"ticking the monitoring option or open 'Erase Web Elements' GM menu and hit its 'OK' button.\nInternal code:"+reply_sel+"\n\n Ancestor:"+nodeInfo(ancErased));
console.info("Already erasing", ancErased, nodeInfo(ancErased),". Your selector", reply_sel);
hlightAndsetsel(0,"off","restore");
checkif_reject("Ancestor Already");
return true;
}
}
function updateErasedElementsLists(webpage_only, reply_sel, complete_rm, checkif_resolve, checkif_reject) {
if (!webpage_only)
erasedElementsListCmd("add", reply_sel+" site");
else
erasedElementsListCmd("add", reply_sel); // btn1 -> null, btn2 -> "<string>" null == undefined
if (erasedElementsListCmd("rm", $(reply_sel).find(".Web-Eraser-ed")))
console.info("Removed child selectors of", reply_sel);
finishedDialog(complete_rm, reply_sel, checkif_resolve);
}
function finishedDialog(complete_rm, reply_sel, checkif_resolve){
hlightAndsetsel(0,"off","restore");
if (complete_rm)
preferences.zaplists.add(reply_sel);
checkif_resolve([true, reply_sel]);
}
function openErasureConfirmation(target){
target = prehitch(target);
const userMsg = gobj.permanentErasureUserMessage;
$(document).keypress(keypressHandler);
const tooltip = gobj.permanentErasureUserTooltip;
const s_prom = sconfirm(userMsg,"Cancel","OK", null, tooltip);
const dialog = s_prom.dialog; // dialog is classed .ui-dialog.
//function addClickBoxesXpath(dialog, target);
appendPermCheckboxes(dialog);
makePreferencesClickable(dialog);
handleXpathInputDisplay(dialog, target);
return s_prom;
}
function appendPermCheckboxes(dialog) {
const buttonpane = dialog.find(".ui-dialog-buttonpane");
buttonpane.append("<div><input id=sfswe-checkbox7 type=checkbox style='vertical-align:middle'>"
+"<label style='display:inline'> Remove just from this page (not entire website).</label></div>");
buttonpane.append("<br><div style='margin-top:-10px;float:left;'><input id=sfswe-checkbox6 type=checkbox style='vertical-align:middle'>"
+"<label style='display:inline;'> Completely delete element.</label></div>");
buttonpane.append("<br><div style='margin-top:-10px;'><input id=sfswe-checkbox10 type=checkbox style='margin-left:30px;vertical-align:middle'>"
+"<label style='display:inline;' "
+"title='Temporary-Deletion mode means that when ctrl-click is pressed it will now quickly delete any element on the page. "
+"However, the deletion is temporary and when the page is reloaded all is restored and ctrl-click will then behave as before.'> Enter Temporary-Deletion mode.</label></div>");
}
function makePreferencesClickable(dialog){
dialog.find(".sfs-link").click( e => {
dialog.trigger($.Event("keydown",{keyCode:27, key:"Escape"})); // close prompt and open Prefs dialog.
erasurePreferences();
});
}
function handleXpathInputDisplay(dialog, target) {
const input = $("#sfswe-seledip"), ip = input[0], div_surround = input.next();
div_surround.click( e=> { // a click on input & surround enables it.
ip.disabled = false; ip.setSelectionRange(999, 999);
div_surround.css("display","none");
input.focus();
input.blur(e => {ip.disabled = true; div_surround.css("display",""); });
}); //
hlightAndsetsel(target); // Also sets input value to selector!
setTimeout(function(){dialog[0].scrollIntoView();}, 100);
}
async function eraseIframe() {
await loadLazyResources();
if(!await sconfirm("\nTo erase a page element, click OK below, then place and leave the mouse hovering over the chosen element for 6 seconds."
+"\n\nThis function is used when ctrl-click does not work. "
+"Certain items visible on the page, eg, Iframes cannot be clicked. "
+"Clicking on them results in a new page opening. ")) return;
var current_hover_targ;
window.addEventListener("mouseover", moverScan, false);
function moverScan(e){
current_hover_targ = e.target;
// if(/iframe/i.test(e.target.tagName)) {
setTimeout(function(prev_targ){
if(prev_targ == current_hover_targ) {
window.removeEventListener("mouseover", moverScan, false);
userIOtoEraseElement(e.target, e);
}
}, 6000, current_hover_targ);
}
}
async function erasurePreferences() {
// Called from GM script command menu (Preferences...) and from clickable within ctrl-click prompt.
//
await loadLazyResources();
const erasedElems = getErasedElemsCmd("with site");
const no_sels = !erasedElems ? 0 : erasedElems.split(/,/).length;
// "See checkboxes distantly below to set the script's configutation values."
openPrefsPrompt(no_sels, erasedElems);
}
function openPrefsPrompt(no_sels, erasedElems){
const prompt_promise = sprompt(
"<span style='padding:0;'>Usage:</span><br>Whilst holding down the Control key, make a mouse click on the "
+"webpage—after quitting this dialogue. That will open a dialog to confirm the erasure. "
+"\n\nOn some elements however, ctrl-click is absorbed. In that case choose from this script's "
+"menu: <span class=sfs-link>Erase via mouse hover....</span>"
+"\n\nBelow find an editable, comma-separated list of each deleted element. "
+"Below that see the preferences' checkboxes.\n"
+"\n"+( no_sels ? "Currently there "+(no_sels == 1 ? "is ":"are ")
+no_sels+" below. " : "No element is being deleted.")+"\n\n"
, erasedElems.replace(/,/g,", \n"));
prompt_promise.then(getCheckboxValues);
adaptDialog(prompt_promise.dialog);
}
async function getCheckboxValues([btn, reply_text]){
if (!btn) return; //btn is null when Cancel is hit, true for OK, undefined when Escape. (null is == to undefined!)
preferences.config = {monitor:preferences.config.monitor};
delete preferences.config.monitor[gobj.website];
if ($("#sfswe-checkbox:checked").length) preferences.config.noAnimation = "checked";
if ($("#sfswe-checkbox2:checked").length) preferences.config.keepLayout = "checked";
if ($("#sfswe-checkbox3:checked").length) preferences.config.hideCurtains = "checked";
if ($("#sfswe-checkbox5:checked").length) preferences.config.monitor[gobj.website] = "checked";
if ($("#sfswe-checkbox9:checked").length) await exportImportScriptData();
else if ($("#sfswe-checkbox4:checked").length) setOwnCurtains();
else savePreferences(reply_text);
};//getCheckboxValues()
function adaptDialog(dialog){
const keep_layout = preferences.config.keepLayout;
dialog.find(".ui-dialog-buttonpane").prepend(
"<div class=sfswe-ticks style='float:left;font-size:10px;'>" //width:78%;
+"<input id=sfswe-checkbox2 type=checkbox style='float:left;vertical-align:middle;"+(!keep_layout?" margin:0 3px;":"")+"' "+keep_layout+"> <label>Preserve layout (in general).</label>"
+(keep_layout ? "<input id=sfswe-checkbox3 type=checkbox style='vertical-align:middle;margin:0 3px 0 10px;height:12px;'"+(preferences.config.hideCurtains||"")+"> <label title='Leaves a blank space over deleted item.'>Also hide curtains.</label>" : "")
+"<br><input id=sfswe-checkbox type=checkbox style='vertical-align:middle; margin-left:3px;'"+(preferences.config.noAnimation||"")+"> <label>Disable animation (in general).</label>"
+"<br><input id=sfswe-checkbox4 type=checkbox style='vertical-align:middle; margin-left:3px;'> <label title='Check box then hit ok'>Set your own curtains' image.</label>"
+"<input id=sfswe-checkbox5 type=checkbox style='vertical-align:middle;margin-left:15px;'"+(preferences.config.monitor[gobj.website]||"")+"> "
+"<label>Monitor this website for new elements.</label>"
+"<br><input id=sfswe-checkbox9 type=checkbox style='vertical-align:middle; margin-left:15px;'>"+" <label title='Check box then hit ok'>Export/Import script's stored data.</label>"
+"</div>"
);
dialog.find("input:checkbox").css({height:12});
dialog.find(".ui-dialog-content").attr("title","WebEraser userscript.\n"+gobj.webpage+"\n\nCurrent matches at this webpage:\n");
dialog.find(".sfs-link").click(e => {
dialog.trigger($.Event("keydown",{keyCode:27, key:"Escape"})); // close prompt and open Prefs dialog.
eraseIframe();});
}
async function exportImportScriptData() {
const nvs = [], array_of_keys = await GM_listValues();
for (let n of array_of_keys) {
nvs.push( { name:n, value_str: await GM_getValue(n) } );
}
sprompt("Stored data, export by copying the entire string below. Import by pasting that entire string below.", JSON.stringify(nvs, null,"\t"))
.then(async function([btn, reply_text]){ // pretty print json
if(!btn) return;
const new_nvs = JSON.parse(reply_text);
for(let obj of new_nvs) {
alert("setting with given name:"+obj.name+", value:"+obj.value_str);
await GM_setValue(obj.name, obj.value_str);
}
});
}
function setOwnCurtains(){
toggleCurtains();
const subpromt = sprompt("Please enter http address of curtain image to be used. If giving left and right images separate with a space. "
+"Leave empty to reset. Accepts base64 image strings.","");
subpromt.dialog.attr("title","Perhaps try a quaint example; one found with an image search for 'curtains':\n\thttp://www.divadecordesign.com/wp-content/uploads/2015/09/lace-curtains-5.jpg");
subpromt.then(function([btn2, reply2]){
if (btn2) { setValue("ownImageAddr", reply2);
gobj.curtain_icon = reply2||gobj.whitecurtains;
gobj.curtain_slim_icon = reply2||gobj.whitecurtainsoriginal;
gobj.curtain_wide_icon = reply2||gobj.whitecurtainstriple;
$(".WebEraserCurtain").attr("src", gobj.curtain_icon); }
toggleCurtains(); });
}
function savePreferences(reply_text) {
console.log("savePreferences", reply_text);
reply_text = reply_text.replace(/\s*,\s*/g,",").replace(/(?=[^,])\n(?=[^,])/g,",").split(/,/); // , newline->comma if none; if no comma all is put in [0]
try{ $(reply_text); } catch(e){ alert("Bad selector given."); throw(e);}
if(reply_text.length)
fitEachSelector(reply_text);
persistSelectors();
effectPageUpdate();
}
function fitEachSelector(reply_text) {
preferences.page_erasedElems = []; preferences.site_erasedElems = [];
buildSelectorArray(reply_text);
preferences.site_erasedElems = preferences.site_erasedElems.toString();
preferences.page_erasedElems = preferences.page_erasedElems.toString();
}
function buildSelectorArray(reply_text){
const duplicates = {};
$(reply_text).each((i, str) => {
if (str == "") return;
if (duplicates[str]) return;
duplicates[str] = true;
str = str.trim();
if (/\ssite$/.test(str)) preferences.site_erasedElems.push(str.replace(/\ssite$/,""));
else preferences.page_erasedElems.push(str);
});
}
function persistSelectors() {
setValue("config", preferences.config);
console.log("SetValue on preferences .config to:", preferences.config);
setValue(gobj.website+":erasedElems", preferences.site_erasedElems);
setValue(gobj.webpage+":erasedElems", preferences.page_erasedElems);
preferences.zaplists.update();
}
function effectPageUpdate() {
openCurtains();
$(".Web-Eraser-ed").each(unerase);
$(".CurtainRod").remove();
setTimeout(inner_eraseElements, 1000,"prompt"); //'cos openCurtains takes time
//inner_eraseElements("fromPrompt");
}
function unerase(){
const self = $(this);
self.css({display: self.data("sfswe-display"), visibility: self.data("sfswe-visibility")});
self.removeClass("Web-Eraser-ed");
};
function inner_eraseElements(from) {
var erasedElems = getErasedElemsCmd();
const len = erasedElems.length, erasedElems_ar = erasedElems.split(/,/), nomatch = [];
var count = 0;
if (erasedElems_ar[0] == "")
erasedElems_ar.shift(); //fix split's creation of array length one for empty string.
var theErased = $(".Web-Eraser-ed");
theErased.removeClass("Web-Eraser-ed");
({erasedElems, count} = doEachErasure());
if (gobj.iframe || count == 0)
return;
theErased = $(".Web-Eraser-ed");
observeThings();
if (len == 0) observeThings("off");
var ieemsg = prefMsg(count);
printUserInfoToConsole(len, nomatch, count, from);
//// Nested functions:
function doEachErasure(){
erasedElems_ar.forEach((sel, i) => {
erasedElems = $(sel); //Array.from(document.querySelectorAll(sel)); //$(sel), jQ cannot find duplicate ids.
if (erasedElems.length == 0) {
let erasedElems_sp = $(stripClasses(sel));
if(erasedElems_sp.length == 1)
erasedElems = erasedElems_sp;
}
count = curtainOrUndisplayThose(sel);
if (erasedElems.length == 0 && sel) nomatch.push(sel);
});
return {erasedElems, count};
}
function curtainOrUndisplayThose(sel) {
erasedElems.each(function(){
const eld = this, el = $(eld);
if(/delay|focus/.test(from) && alreadyClosed(el, eld))
return;
markAndErase(el, eld, sel);
count++;
});
return count;
}
function markAndErase(el, eld, sel) {
markForTheCurtains(el, eld, sel);
const no_anima = preferences.config.noAnimation, keep_layout = preferences.config.keepLayout;
if (no_anima && !keep_layout)
eld.style.setProperty("display","none","important");
else if (el.css("display")!="none")
closeCurtains(el, no_anima, measureForCurtains);
}
function alreadyClosed(el, eld) {
const crod = jQuery.data(eld,"rod-el");
if (crod && /^sfswediv/i.test(crod[0].tagName)) {
el.addClass("Web-Eraser-ed");
return true;
}
}
function printUserInfoToConsole() {
if (theErased.length == 0) return; ////////////////////
if (nomatch.length) {
console.info("WebEraser message: no match for the following selectors at", gobj.webpage+":");
nomatch.forEach(nom => console.info("\t", nom));
//console.log("Q:", document.querySelectorAll("body *"), typeof $$)
}
addIndivMsgs();
ieemsg+="(phase:"+from+")";
count = 0;
console.info(ieemsg);
}
function prefMsg(){
return "Userscript WebEraser has selectors to erase. "+count+(count == 1 ? " element that was":" elements that were")+" present on page at site: "+gobj.website
+".\nSee GM menu command Erase Web Elements to check and edit selector list. "
+(preferences.config.keepLayout ? "" : "Keep layout is not ticked.")
+(preferences.config.noAnimation ? "Animation is off." : "")
+(preferences.config.hideCurtains ? "Hide curtains is ticked." : "");
}
function addIndivMsgs() {
theErased.each(function(i){
const that = $(this), sel = that.attr("selector-this-matched-we");
const onzaplist = preferences.zaplists.which(sel), rod = jQuery.data(this,"rod-el");
const is_an_overlay = (rod && rod.hasClass("sfswe-overlay")); //that.prev().hasClass("sfswe-overlay");
ieemsg+="\n"+(i+1)+":"+sel;
ieemsg+=".\t\t"
+(is_an_overlay ? "=> Considered as an Overlay, takes up > 90% (was 0.6) of window, deleted."
: onzaplist.zap ? " => complete erasure."
: onzaplist.keep_layout ? " => erase but keep layout."
: "" );
});
return ieemsg;
}
} // end inner_eraseElements().
function closeCurtains(elem, noAnimKeepLayout, finishedCB = x => x) { // a bracketing function to avoid class 'this' pollution.
const [curtainRod, lrcurtains] = getCurtainParts(getPrevCurtains());
const onzaplist = preferences.zaplists.which(elem),
hide_curtains = preferences.config.hideCurtains;
if (noAnimKeepLayout)
eraseWithoutFuss();
else animateClose(finishedCB);
return false; // if run from event handler prevents default.
function getCurtainParts(old_curtained){
let curtainRod, lrcurtains;
if ( ! old_curtained || ! old_curtained.is(elem))
[curtainRod, lrcurtains] = makeCurtains(elem, noAnimKeepLayout);
else {
curtainRod = elem.siblings("sfswediv");
lrcurtains = curtainRod.children();
}
curtainRod.css("display","");
return [curtainRod, lrcurtains];
}
function getPrevCurtains(){
const wediv = elem.siblings("sfswediv");
return wediv.length ? jQuery.data(wediv[0],"covered-el") : null;
}
function eraseWithoutFuss() {
lrcurtains.css({width:"51%"});
if (onzaplist.zap) { curtainRod.css({display:"none"}); elem[0].style.setProperty("display","none","important");} // "none" triggers monitor if on.
else if (onzaplist.keep_layout||hide_curtains||curtainRod.hasClass("sfswe-overlay")){
curtainRod.css({visibility:"hidden", display:""});
elem[0].style.setProperty("visibility","hidden","important");
}
measureForCurtains();
}
function animateClose() {
// Do animated curtain closing, then, perhaps, fade out.
const that = animateClose; if (!that.final_curtain) that.final_curtain = 0;
const keep_layout = preferences.config.keepLayout;
that.final_curtain++;
profileTimer("start-animation");
manimate(lrcurtains,["width", 15,"%"], 1000, 2);
manimate(lrcurtains,["width", 51,"%", 1000], 1000, 5,
function() { endManimate.call(this, keep_layout, that);});
}
function endManimate(keep_layout, that) {
profileTimer("end-animation"); // this from eppurSiMuove is the right curtain obj.
lrcurtains.css("width","51%");
curtainRod.css("visibility","visible");
const el = jQuery.data(this.parentNode, "covered-el")||$();
if (!keep_layout || curtainRod.hasClass("sfswe-overlay")||onzaplist.zap)
fadeOut(el, curtainRod, that, finishedCB);
else if (hide_curtains||onzaplist.keep_layout)
fadeFully(el, curtainRod, that, finishedCB);
else if (--that.final_curtain == 0)
finishedCB(curtainRod);
}
function fadeOut(el, that) {
el.add(curtainRod).delay(200).fadeOut(500, function(){
this.style.setProperty("display","none","important"); // triggers monitor if on.
if (el[0] == this && --that.final_curtain == 0)
finishedCB();
});
}
function fadeFully(el, that){
el.add(curtainRod).delay(200).fadeOut(
1000, function(){
this.style.setProperty("visibility","hidden","important");
this.style.setProperty("display", $(this).data("sfswe-display"),"important"); //triggers monitor.
curtainRod.css({visibility:"hidden", display:""});
curtainRod.remove();
let itsOnLastCurtain = (el[0] == this && --that.final_curtain == 0);
if (itsOnLastCurtain) finishedCB();
});
}
} // end closeCurtains().
function keypressHandler(event) { //try { //while prompt is open.
switch(event.key) {
case "w": widen(); break;
case "n": narrow(); break;
default: return; }
return false;
}
async function init_async_globs() { // all globs asynchronously set.
profileTimer("init phase2-start");
preferences.zaplists = new ZaplistComposite();
await preferences.zaplists.update(); //depends on site/page_erasedElems being read first.
gobj.ownImageAddr = await getValue("ownImageAddr","");
await initCurtainGlobs(); // This instruction when in TM using GM_ version, is very slow, it returns a base64 string, 2, 928, 417 bytes in length. Slow on chromium/TM, ok on FF.
profileTimer("init phase2-end");
}
async function initCurtainGlobs() {
gobj.whitecurtains = await getResourceUrl("whiteCurtains");
gobj.whitecurtainsoriginal = await getResourceUrl("whiteCurtainsOrig");
gobj.whitecurtainstriple = await getResourceUrl("whiteCurtainsTrpl");
gobj.whitecurtainsxsm = await getResourceUrl("whiteCurtainsXsm");
gobj.curtain_icon = gobj.ownImageAddr|| gobj.whitecurtains;
gobj.curtain_slim_icon = await getValue("ownImageAddr","")||gobj.whitecurtainsoriginal;
gobj.curtain_xslim_icon = await getValue("ownImageAddr","")||gobj.whitecurtainsxsm;
gobj.curtain_wide_icon = await getValue("ownImageAddr","")||gobj.whitecurtainstriple;
}
function installEventHandlers(phase2) {
if(!phase2) evhandlersPhase1();
else evhandlersPhase2();
}
function evhandlersPhase1() {
document.addEventListener("scroll", function(e){ if (!gobj.overlay) return; e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();}, true);
window.addEventListener("click", handleClick, true);
window.addEventListener("mousedown", handleClick, true);
window.addEventListener("message", postMessageHandler, false);
if(gobj.iframe) window.installedEHs = true;
//console.log("installed handlers, window.mousedown, at:", location.href,". In iframe?", iframe);
}
function evhandlersPhase2() { // phase2
$("iframe").each(function(){
const fwin = this.contentWindow; try{ //perhaps permission error due to iframe origin.
if (!fwin.installedEHs) {
fwin.addEventListener.call(fwin,"mousedown", handleClick, true);
fwin.addEventListener.call(fwin,"message", postMessageHandler, false);
//despite use of call(), event is still triggered in this context not in iframe's hence use of frameElement.
}} catch(e){};
});
}
function prevDef(e) {
if (e.preventDefault) {
e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); }
}
function postMessageHandler(e){ // window.postMessage comms
const itsaMsgForWebEraser = ( e.data?.type == "sfswe-iframe-click");
if (itsaMsgForWebEraser) {
if (gobj.iframe) {
window.parent.postMessage({type:"sfswe-iframe-click", code:++e.data.code},"*");
return;
}
const iframeEl = findIframe(e); //$("iframe, embed").each((i, el)=>{ !! removed, no jQ in iframe.
handleClick({target:iframeEl},"click_from_nested_iframe");
}
}
function findIframe(e){
for (let el of document.querySelectorAll("iframe, embed")) {
if (el.contentWindow == e.source ||e.data.src == el.src) {
return el;
}
}
}
function getSelectorWithNearestId(target, exclude_classes) { // need extended jquery for :regexp
ensure_jquery_extended();
const nearestNonNumericId = target.closest(":regexp(id,^\\D+$)").attr("id");
var sel, nnnid = nearestNonNumericId; //closest also checks target
if (nnnid && $("[id = "+nnnid+"]").length>1) {
nnnid = "";
gobj.ignoreIdsDupped = true;
} // Page error duplicate ids, ignore id.
return getFullSelector(nnnid, sel, target, exclude_classes);
}
function getFullSelector(nnnid, sel, target, exclude_classes){
if (nnnid)
nnnid = $("#"+nnnid).prop("tagName")+"#"+nnnid; //cos of jQ & multiple ids.
if ($(nnnid).is(target))
sel = nnnid;
else {
sel = selector(target, $(nnnid), true, 0, exclude_classes); //ok if nnnid is undefined id.
if (!sel)
sel = nnnid; //both target and $(nnnid) are same element.
else if(nnnid && !/^html/i.test(nnnid))
sel = nnnid+sel;
}
return sel;
}
function getErasedElemsCmd(cmd, el){
const els = preferences.page_erasedElems, pels = preferences.page_erasedElems;
var sels = preferences.site_erasedElems;
switch(cmd) {
case "match el": return el.is($(getErasedElemsCmd()));
case "isPage": return el.is($(pels));
case "count": return getErasedElemsCmd().split(/,/).reduce(function(prev_res, sel){return prev_res+$(sel).length;}, 0);
case "with site": sels = sels.replace(/,/g," site,")+(sels ? " site" : ""); // see reverse of this in erasedElementsListCmd() and erasurePreferences().
default: return pels + (sels && pels ? "," : "") + sels; // if (justpels_ar) return pels.split(","); //webpage elements.
}
}
function erasedElementsListCmd(cmd, str, str2) {
//console.log("erasedElementsListCmd, cmd:", cmd, "str:", str,"str2:", str2, "ErasedElems:", getErasedElemsCmd());
var sitewide, retval;
var cmdObject = { "isthere?": isStrThere, add: addErasureSel, mv: moveSelToNewOne, rm: removeSelectorFromErasedElemsList };
return cmdObject[cmd](str, str2);
}
function addErasureSel(str){
if (!erasedElementsListCmd("isthere?", str)) {
var sitewide;
checkSite();
appendRightStr();
storeChanges();
}
function checkSite(){
if (/\ssite$/.test(str)) {
sitewide = true;
str = str.replace(/\s+site$/,"");
}
}
function appendRightStr() {
if (sitewide)
preferences.site_erasedElems += preferences.site_erasedElems ? ","+str : str;
else
preferences.page_erasedElems += preferences.page_erasedElems ? ","+str : str;
$(str).each(function() {
$(this).data("sfswe-oldval", $(this).css(["display","visibility","height","width"]));
});
}
}
function isStrThere(str) {
return getErasedElemsCmd().split(/,/).includes(str);
}
function moveSelToNewOne(str, str2) {
erasedElementsListCmd("rm", str);
erasedElementsListCmd("add", str2);
}
function removeSelectorFromErasedElemsList(str){
if (str instanceof $) {
str.each(function(){
erasedElementsListCmd("rm", $(this).attr("#selector-this-matched-we"));
});
return str.length;
}
cutOutOfTheString(str);
storeChanges();
}
function cutOutOfTheString(str){
preferences.page_erasedElems = $.map(
preferences.page_erasedElems.split(/,/),
el => el == str ? null : el.trim()).join(",");
preferences.site_erasedElems = $.map(
preferences.site_erasedElems.split(/,/),
el => el == str ? null : el.trim()).join(",");
}
function storeChanges(){
setValue(gobj.website+":erasedElems", preferences.site_erasedElems);
setValue(gobj.webpage+":erasedElems", preferences.page_erasedElems);
preferences.zaplists.update();
}
//Blinks are double, one for selected elements, other is only when at top/bottom of narrow/widen chosen.
function hlightAndsetsel(elem, off, restore, mere_highlight) {try{ //also updates prompt with elem's selector.
if (!off)
turnHighlightOn(elem);
else
turnHighlightOff(restore);
}catch(e) {console.error("hlightAndsetsel(), error:", e.lineNumber, e);}}
function turnHighlightOn(elem){
elem = $(elem);
if (elem.length == 0) return;
gobj.trace_elem = $(elem);
const height = gobj.trace_elem.height(),
width = gobj.trace_elem.width();
updatePrompt();
blinkRedBorder(height, width);
}
function blinkRedBorder(height, width){
setTraceBack(height, width);
gobj.bblinker = setInterval(function(){ // normal "selected" blink.
if (gobj.sel_matching_els.length)
gobj.sel_matching_els.toggleClass(gobj.rbcl);
else gobj.trace_elem.toggleClass(gobj.rbcl);
}, 1200);
}
function setTraceBack(height, width) {
gobj.trace_elem.data("pewiden-trace","true");
gobj.sel_matching_els.addClass(gobj.rbcl);
gobj.trace_elem.elh = gobj.trace_elem[0].style.height;
gobj.trace_elem.elw = gobj.trace_elem[0].style.width;
gobj.trace_elem.height(height- 2*gobj.border_width);
gobj.trace_elem.width(width- 2*gobj.border_width);
}