-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpplxport.user.js
More file actions
3229 lines (2815 loc) · 122 KB
/
pplxport.user.js
File metadata and controls
3229 lines (2815 loc) · 122 KB
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 Perplexity.ai Chat Exporter
// @namespace https://github.com/ckep1/pplxport
// @version 2.7.1
// @description Export Perplexity.ai conversations as markdown with configurable citation styles
// @author Chris Kephart
// @match https://www.perplexity.ai/*
// @grant GM_getValue
// @grant GM_setValue
// @run-at document-idle
// @license MIT
// ==/UserScript==
(function () {
"use strict";
// ============================================================================
// CONFIGURATION & CONSTANTS
// ============================================================================
const DEBUG = false;
const console = DEBUG ? window.console : { log() {}, warn() {}, error() {} };
// Style options
const CITATION_STYLES = {
ENDNOTES: "endnotes",
FOOTNOTES: "footnotes",
INLINE: "inline",
PARENTHESIZED: "parenthesized",
NAMED: "named",
NONE: "none",
};
const CITATION_STYLE_LABELS = {
[CITATION_STYLES.ENDNOTES]: "Endnotes",
[CITATION_STYLES.FOOTNOTES]: "Footnotes",
[CITATION_STYLES.INLINE]: "Inline",
[CITATION_STYLES.PARENTHESIZED]: "Parenthesized",
[CITATION_STYLES.NAMED]: "Named",
[CITATION_STYLES.NONE]: "No Citations",
};
const CITATION_STYLE_DESCRIPTIONS = {
[CITATION_STYLES.ENDNOTES]: "[1] in text with sources listed at the end",
[CITATION_STYLES.FOOTNOTES]: "[^1] in text with footnote definitions at the end",
[CITATION_STYLES.INLINE]: "[1](url) - Clean inline citations",
[CITATION_STYLES.PARENTHESIZED]: "([1](url)) - Inline citations in parentheses",
[CITATION_STYLES.NAMED]: "([wikipedia](url)) - Uses domain names",
[CITATION_STYLES.NONE]: "Remove all citations from the text",
};
const FORMAT_STYLES = {
FULL: "full", // Include User/Assistant tags and all dividers
CONCISE: "concise", // Just content, minimal dividers
};
const FORMAT_STYLE_LABELS = {
[FORMAT_STYLES.FULL]: "Full",
[FORMAT_STYLES.CONCISE]: "Concise",
};
const EXPORT_METHODS = {
DOWNLOAD: "download",
CLIPBOARD: "clipboard",
};
const EXPORT_METHOD_LABELS = {
[EXPORT_METHODS.DOWNLOAD]: "Download File",
[EXPORT_METHODS.CLIPBOARD]: "Copy to Clipboard",
};
const EXTRACTION_METHODS = {
DIRECT_DOM: "direct_dom",
EXPORT: "export",
COPY_BUTTONS: "copy_buttons",
};
// Global citation tracking for consistent numbering across all responses
const globalCitations = {
urlToNumber: new Map(), // normalized URL -> citation number
citationRefs: new Map(), // citation number -> {href, sourceName, normalizedUrl}
nextCitationNumber: 1,
reset() {
this.urlToNumber.clear();
this.citationRefs.clear();
this.nextCitationNumber = 1;
},
addCitation(url, sourceName = null) {
const normalizedUrl = normalizeUrl(url);
if (!this.urlToNumber.has(normalizedUrl)) {
this.urlToNumber.set(normalizedUrl, this.nextCitationNumber);
this.citationRefs.set(this.nextCitationNumber, {
href: url,
sourceName,
normalizedUrl,
});
this.nextCitationNumber++;
}
return this.urlToNumber.get(normalizedUrl);
},
getCitationNumber(url) {
const normalizedUrl = normalizeUrl(url);
return this.urlToNumber.get(normalizedUrl);
},
save() {
return {
urlToNumber: new Map(this.urlToNumber),
citationRefs: new Map(this.citationRefs),
nextCitationNumber: this.nextCitationNumber,
};
},
restore(state) {
this.urlToNumber = new Map(state.urlToNumber);
this.citationRefs = new Map(state.citationRefs);
this.nextCitationNumber = state.nextCitationNumber;
},
merge(state) {
for (const [url, num] of state.urlToNumber) {
if (!this.urlToNumber.has(url)) {
this.urlToNumber.set(url, num);
this.citationRefs.set(num, state.citationRefs.get(num));
if (num >= this.nextCitationNumber) this.nextCitationNumber = num + 1;
}
}
},
};
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
// Get user preferences
function getPreferences() {
return {
citationStyle: GM_getValue("citationStyle", CITATION_STYLES.PARENTHESIZED),
formatStyle: GM_getValue("formatStyle", FORMAT_STYLES.FULL),
addExtraNewlines: GM_getValue("addExtraNewlines", true),
exportMethod: GM_getValue("exportMethod", EXPORT_METHODS.DOWNLOAD),
includeFrontmatter: GM_getValue("includeFrontmatter", true),
titleAsH1: GM_getValue("titleAsH1", false),
extractionMethod: GM_getValue("extractionMethod", EXTRACTION_METHODS.DIRECT_DOM),
};
}
// Extract source name from text, handling various formats
function extractSourceName(text) {
if (!text) return null;
// Clean the text
text = text.trim();
// If it's a pattern like "rabbit+2", "developer.mozilla+1", extract the source name
const plusMatch = text.match(/^(.+?)\+\d+$/);
if (plusMatch) {
return plusMatch[1].toLowerCase();
}
// If it's just text without numbers, use it as is (lowercased)
const cleanName = text.toLowerCase();
if (cleanName.length > 0) {
return cleanName;
}
return null;
}
// Normalize URL by removing fragments (#) to group same page citations
function normalizeUrl(url) {
if (!url) return null;
try {
const urlObj = new URL(url);
// Remove the fragment (hash) portion
urlObj.hash = "";
return urlObj.toString();
} catch (e) {
// If URL parsing fails, just remove # manually
return url.split("#")[0];
}
}
// Extract domain name from URL for named citations
function extractDomainName(url) {
if (!url) return null;
try {
const urlObj = new URL(url);
let domain = urlObj.hostname.toLowerCase();
// Remove www. prefix
domain = domain.replace(/^www\./, "");
// Get the main domain part (before first dot for common cases)
const parts = domain.split(".");
if (parts.length >= 2) {
// Handle special cases like co.uk, github.io, etc.
if (parts[parts.length - 2].length <= 3 && parts.length > 2) {
return parts[parts.length - 3];
} else {
return parts[parts.length - 2];
}
}
return parts[0];
} catch (e) {
return null;
}
}
// ============================================================================
// DOM HELPER FUNCTIONS
// ============================================================================
function getThreadContainer() {
return document.querySelector('.max-w-threadContentWidth, [class*="threadContentWidth"]') || document.querySelector("main") || document.body;
}
function getScrollRoot() {
const thread = getThreadContainer();
const candidates = [];
let node = thread;
while (node && node !== document.body) {
candidates.push(node);
node = node.parentElement;
}
const scrollingElement = document.scrollingElement || document.documentElement;
candidates.push(scrollingElement);
let best = null;
for (const el of candidates) {
try {
const style = getComputedStyle(el);
const overflowY = (style.overflowY || style.overflow || "").toLowerCase();
const canScroll = el.scrollHeight - el.clientHeight > 50;
const isScrollable = /auto|scroll|overlay/.test(overflowY) || el === scrollingElement;
if (canScroll && isScrollable) {
if (!best || el.scrollHeight > best.scrollHeight) {
best = el;
}
}
} catch (e) {
// ignore
}
}
return best || scrollingElement;
}
function isInViewport(el, margin = 8) {
const rect = el.getBoundingClientRect();
const vh = window.innerHeight || document.documentElement.clientHeight;
const vw = window.innerWidth || document.documentElement.clientWidth;
return rect.bottom > -margin && rect.top < vh + margin && rect.right > -margin && rect.left < vw + margin;
}
function isCodeCopyButton(btn) {
const testId = btn.getAttribute("data-testid");
const ariaLower = (btn.getAttribute("aria-label") || "").toLowerCase();
if (testId === "copy-code-button" || testId === "copy-code" || (testId && testId.includes("copy-code"))) return true;
if (ariaLower.includes("copy code")) return true;
if (btn.closest("pre") || btn.closest("code")) return true;
return false;
}
function findUserMessageRootFromElement(el) {
let node = el;
let depth = 0;
while (node && node !== document.body && depth < 10) {
if (node.querySelector && (node.querySelector("button[data-testid='copy-query-button']") || node.querySelector("button[aria-label='Copy Query']") || node.querySelector("span[data-lexical-text='true']") || node.querySelector("span.select-text"))) {
return node;
}
node = node.parentElement;
depth++;
}
return el.parentElement || el;
}
function findUserMessageRootFrom(button) {
let node = button;
let depth = 0;
while (node && node !== document.body && depth < 10) {
if (node.querySelector && (node.querySelector(".whitespace-pre-line.text-pretty.break-words") || node.querySelector("span[data-lexical-text='true']") || node.querySelector("span.select-text"))) {
return node;
}
node = node.parentElement;
depth++;
}
return button.parentElement || button;
}
function findAssistantMessageRootFrom(button) {
let node = button;
let depth = 0;
while (node && node !== document.body && depth < 10) {
// An assistant message root should contain the prose answer block
if (node.querySelector && node.querySelector(".prose.text-pretty.dark\\:prose-invert, [class*='prose'][class*='prose-invert'], [data-testid='answer'], [data-testid='assistant']")) {
return node;
}
node = node.parentElement;
depth++;
}
return button.parentElement || button;
}
// ============================================================================
// SCROLL & NAVIGATION HELPERS
// ============================================================================
async function pageDownOnce(scroller, delayMs = 90, factor = 0.9) {
if (!scroller) scroller = getScrollRoot();
const delta = Math.max(200, Math.floor(scroller.clientHeight * factor));
scroller.scrollTop = Math.min(scroller.scrollTop + delta, scroller.scrollHeight);
await new Promise((r) => setTimeout(r, delayMs));
}
function simulateHover(element) {
try {
const rect = element.getBoundingClientRect();
const x = rect.left + Math.min(20, Math.max(2, rect.width / 3));
const y = rect.top + Math.min(20, Math.max(2, rect.height / 3));
const opts = { bubbles: true, clientX: x, clientY: y };
element.dispatchEvent(new MouseEvent("mouseenter", opts));
element.dispatchEvent(new MouseEvent("mouseover", opts));
element.dispatchEvent(new MouseEvent("mousemove", opts));
} catch (e) {
// best effort
}
}
async function waitForFocus(timeoutMs = 30000) {
if (document.hasFocus()) return true;
const startTime = Date.now();
const overlay = document.getElementById('perplexity-focus-overlay');
if (overlay) {
const titleEl = overlay.querySelector("#perplexity-focus-overlay-title");
const subtitleEl = overlay.querySelector("#perplexity-focus-overlay-subtitle");
if (titleEl) titleEl.textContent = "Click here to continue export";
if (subtitleEl) subtitleEl.textContent = "Export paused - page needs focus to read clipboard";
overlay.style.display = 'flex';
}
while (!document.hasFocus() && (Date.now() - startTime) < timeoutMs) {
window.focus();
await new Promise(r => setTimeout(r, 100));
}
if (overlay) overlay.style.display = 'none';
return document.hasFocus();
}
async function readClipboardWithRetries(maxRetries = 3, delayMs = 60) {
let last = "";
for (let i = 0; i < maxRetries; i++) {
// Wait for focus before attempting clipboard read
if (!document.hasFocus()) {
const gotFocus = await waitForFocus(10000);
if (!gotFocus) {
console.warn('Lost focus during clipboard read, retrying...');
}
}
try {
const text = await navigator.clipboard.readText();
if (text && text.trim() && text !== last) {
return text;
}
last = text;
} catch (e) {
// keep retrying
}
await new Promise((r) => setTimeout(r, delayMs));
}
try {
return await navigator.clipboard.readText();
} catch {
return "";
}
}
// Click expanders like "Show more", "Read more", etc. Best-effort
const clickedExpanders = new WeakSet();
function findExpanders(limit = 8) {
const candidates = [];
const patterns = /(show more|read more|view more|see more|expand|load more|view full|show all|continue reading)/i;
const els = document.querySelectorAll('button, a, [role="button"]');
for (const el of els) {
if (candidates.length >= limit) break;
if (clickedExpanders.has(el)) continue;
const label = (el.getAttribute("aria-label") || "").trim();
const text = (el.textContent || "").trim();
if (patterns.test(label) || patterns.test(text)) {
// avoid code-block related buttons
if (el.closest("pre, code")) continue;
// avoid deep research card fullscreen/view buttons
if (/full screen|fullscreen/i.test(label) || /full screen|fullscreen/i.test(text)) continue;
// avoid external anchors that might navigate
if (el.tagName && el.tagName.toLowerCase() === "a") {
const href = (el.getAttribute("href") || "").trim();
const target = (el.getAttribute("target") || "").trim().toLowerCase();
const isExternal = /^https?:\/\//i.test(href);
if (isExternal || target === "_blank") continue;
}
candidates.push(el);
}
}
return candidates;
}
async function clickExpandersOnce(limit = 6) {
const expanders = findExpanders(limit);
if (expanders.length === 0) return false;
for (const el of expanders) {
try {
clickedExpanders.add(el);
el.dispatchEvent(new MouseEvent("mouseenter", { bubbles: true }));
await new Promise((r) => setTimeout(r, 50));
el.click();
await new Promise((r) => setTimeout(r, 150));
} catch {}
}
// allow expanded content to render
await new Promise((r) => setTimeout(r, 250));
return true;
}
// ============================================================================
// BUTTON HELPER FUNCTIONS
// ============================================================================
function getViewportQueryButtons() {
const buttons = Array.from(document.querySelectorAll('button[data-testid="copy-query-button"], button[aria-label="Copy Query"]'));
return buttons.filter((btn) => isInViewport(btn) && !btn.closest("pre,code"));
}
function getViewportResponseButtons() {
// Just check for any SVG element, or multiple possible SVG classes
const buttons = Array.from(document.querySelectorAll('button[aria-label="Copy"]')).filter((btn) => {
return btn.querySelector("svg.tabler-icon") || btn.querySelector("svg.tabler-icon-copy") || btn.querySelector("svg");
});
return buttons.filter((btn) => isInViewport(btn) && !btn.closest("pre,code"));
}
async function clickVisibleButtonAndGetClipboard(button) {
try {
window.focus();
simulateHover(button);
await new Promise((r) => setTimeout(r, 40));
button.focus();
button.click();
await new Promise((r) => setTimeout(r, 60));
return await readClipboardWithRetries(3, 60);
} catch (e) {
return "";
}
}
// ============================================================================
// DEEP RESEARCH DETECTION & HELPERS
// ============================================================================
function isDeepResearch() {
// Old side panel format
if (document.querySelector('[class*="search-side-content"]')) return true;
if (document.querySelector('button[data-testid="asset-card-open-button"]')) return true;
// New inline card: has "Copy contents" or "Copy as Markdown" alongside "steps completed"
if (document.querySelector('button[aria-label="Copy contents"]')) return true;
if ([...document.querySelectorAll('button')].find(b => /copy as markdown/i.test(b.textContent))) return true;
// "steps completed" alone (old format without card) → treat as standard conversation
return false;
}
async function openDeepResearchPanel() {
if (document.querySelector('[class*="search-side-content"]')) return true;
// New inline formats: report is already visible, no panel to open
if (document.querySelector('button[aria-label="Copy contents"]')) return true;
if ([...document.querySelectorAll('button')].find(b => /copy as markdown/i.test(b.textContent))) return true;
// Old format: try opening side panel via card button
const cardBtn = document.querySelector('button[data-testid="asset-card-open-button"]');
if (!cardBtn) return false;
cardBtn.click();
for (let i = 0; i < 30; i++) {
await new Promise(r => setTimeout(r, 200));
if (document.querySelector('[class*="search-side-content"]')) return true;
}
return false;
}
async function interceptCopyContents() {
const commId = '__pplxport_dr_copy_' + Date.now();
const comm = document.createElement('div');
comm.id = commId;
comm.style.display = 'none';
document.body.appendChild(comm);
const script = document.createElement('script');
script.textContent = `(function(){
var c=document.getElementById("${commId}");
var ow=navigator.clipboard.writeText.bind(navigator.clipboard);
navigator.clipboard.writeText=function(t){
c.textContent=t;
return ow(t);
};
window.__pplxport_copy_cleanup=function(){
navigator.clipboard.writeText=ow;
delete window.__pplxport_copy_cleanup;
};
})();`;
document.documentElement.appendChild(script);
script.remove();
try {
// Expand collapsed report so all citation URLs are in the DOM for scraping
const showFullBtn = [...document.querySelectorAll('button')].find(b => /show full report/i.test(b.textContent));
if (showFullBtn) {
simulateClick(showFullBtn);
await new Promise(r => setTimeout(r, 500));
}
const copyBtn = document.querySelector('button[aria-label="Copy contents"]')
|| [...document.querySelectorAll('button')].find(b => /copy as markdown/i.test(b.textContent));
if (!copyBtn) throw new Error('No copy button found');
simulateClick(copyBtn);
for (let i = 0; i < 30; i++) {
await new Promise(r => setTimeout(r, 100));
if (comm.textContent) break;
}
return comm.textContent || null;
} finally {
const cleanup = document.createElement('script');
cleanup.textContent = 'if(window.__pplxport_copy_cleanup)window.__pplxport_copy_cleanup();';
document.documentElement.appendChild(cleanup);
cleanup.remove();
comm.remove();
}
}
async function scrapeDeepResearchDOM() {
// Expand collapsed report first
const showFullBtn = [...document.querySelectorAll('button')].find(b => /show full report/i.test(b.textContent));
if (showFullBtn) {
simulateClick(showFullBtn);
await new Promise(r => setTimeout(r, 500));
}
// Find the DR card container - walk up from a DR-specific button
// to the nearest ancestor that contains .prose
const anchor = document.querySelector('button[aria-label="Copy contents"]')
|| [...document.querySelectorAll('button')].find(b => /copy as markdown/i.test(b.textContent));
if (!anchor) return null;
let cardContainer = anchor;
for (let d = 0; d < 8 && cardContainer; d++) {
if (cardContainer.querySelector?.('.prose')) break;
cardContainer = cardContainer.parentElement;
}
// Only take leaf prose nodes (skip outer wrappers that contain nested .prose)
const allProse = cardContainer?.querySelectorAll('.prose');
if (!allProse || allProse.length === 0) return null;
const proseEls = [...allProse].filter(p => p.querySelectorAll('.prose').length === 0);
if (proseEls.length === 0) return null;
const parts = [];
for (const prose of proseEls) {
annotateCitationUrls(prose);
const cloned = prose.cloneNode(true);
const md = htmlToMarkdown(cloned.innerHTML, getPreferences().citationStyle, null).trim();
if (md) parts.push(md);
}
const prefs = getPreferences();
const gap = prefs.addExtraNewlines ? '\n\n' : '\n';
return parts.length > 0 ? parts.join(gap) : null;
}
async function interceptExportMarkdown() {
const commId = '__pplxport_dr_capture_' + Date.now();
const comm = document.createElement('div');
comm.id = commId;
comm.style.display = 'none';
document.body.appendChild(comm);
const script = document.createElement('script');
script.textContent = `(function(){
var c=document.getElementById("${commId}");
var oc=HTMLAnchorElement.prototype.click;
var ou=URL.createObjectURL;
URL.createObjectURL=function(o){
var u=ou.call(this,o);
if(o instanceof Blob){o.text().then(function(t){c.textContent=t;});}
return u;
};
HTMLAnchorElement.prototype.click=function(){
if(this.download&&(this.href||"").match(/^(blob|data):/)){
if(this.href.startsWith("data:")){
try{
var p=this.href.split(",");var e=p[1];
if(p[0].indexOf("base64")>-1){
var b=Uint8Array.from(atob(e),function(x){return x.charCodeAt(0);});
c.textContent=new TextDecoder().decode(b);
}else{c.textContent=decodeURIComponent(e);}
}catch(x){}
}
return;
}
return oc.call(this);
};
window.__pplxport_dr_cleanup=function(){
HTMLAnchorElement.prototype.click=oc;
URL.createObjectURL=ou;
delete window.__pplxport_dr_cleanup;
};
})();`;
document.documentElement.appendChild(script);
script.remove();
try {
const exportBtn = Array.from(document.querySelectorAll('button[aria-haspopup="menu"]'))
.find(b => b.textContent.includes('Export'));
if (!exportBtn) throw new Error('Export button not found in side panel');
exportBtn.focus();
simulateClick(exportBtn);
await new Promise(r => setTimeout(r, 500));
const menuItem = Array.from(document.querySelectorAll('[role="menuitem"]'))
.find(m => m.textContent.includes('Download as Markdown'));
if (!menuItem) throw new Error('Download as Markdown menu item not found');
simulateClick(menuItem);
for (let i = 0; i < 30; i++) {
await new Promise(r => setTimeout(r, 100));
if (comm.textContent) break;
}
return comm.textContent || null;
} finally {
const cleanup = document.createElement('script');
cleanup.textContent = 'if(window.__pplxport_dr_cleanup)window.__pplxport_dr_cleanup();';
document.documentElement.appendChild(cleanup);
cleanup.remove();
comm.remove();
}
}
// ============================================================================
// THREAD EXPORT INTERCEPTION (regular threads, NOT deep research)
// ============================================================================
// Fallback extraction method: triggers the three-dot menu's "Export as Markdown"
// on regular threads, intercepts the download, and reformats the content.
// Used automatically as a middle fallback between DOM scan and copy buttons.
function simulateClick(el) {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
el.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, composed: true }));
}
}
async function interceptThreadExportMarkdown() {
// Inject interception into the PAGE context (not userscript sandbox).
// Tampermonkey's @grant sandbox isolates prototype patches, so we inject
// a <script> tag that patches in the page's own JS world.
const commId = '__pplxport_capture_' + Date.now();
const comm = document.createElement('div');
comm.id = commId;
comm.style.display = 'none';
document.body.appendChild(comm);
const script = document.createElement('script');
script.textContent = `(function(){
var c=document.getElementById("${commId}");
var oc=HTMLAnchorElement.prototype.click;
var ou=URL.createObjectURL;
URL.createObjectURL=function(o){
var u=ou.call(this,o);
if(o instanceof Blob){o.text().then(function(t){c.textContent=t;});}
return u;
};
HTMLAnchorElement.prototype.click=function(){
if(this.download&&(this.href||"").match(/^(blob|data):/)){
if(this.href.startsWith("data:")){
try{
var p=this.href.split(",");var e=p[1];
if(p[0].indexOf("base64")>-1){
var b=Uint8Array.from(atob(e),function(x){return x.charCodeAt(0);});
c.textContent=new TextDecoder().decode(b);
}else{c.textContent=decodeURIComponent(e);}
}catch(x){}
}
return;
}
return oc.call(this);
};
window.__pplxport_cleanup=function(){
HTMLAnchorElement.prototype.click=oc;
URL.createObjectURL=ou;
delete window.__pplxport_cleanup;
};
})();`;
document.documentElement.appendChild(script);
script.remove();
try {
// Find the "Thread actions" three-dot menu button
let threeDotBtn = document.querySelector('button[aria-label="Thread actions"]');
if (!threeDotBtn) {
const menuButtons = Array.from(document.querySelectorAll('button[aria-haspopup="menu"]'));
threeDotBtn = menuButtons.find(b => {
if (b.textContent.includes('Export')) return false;
if (!b.querySelector('svg')) return false;
if (b.closest('#perplexity-export-controls')) return false;
return true;
});
}
if (!threeDotBtn) throw new Error('Thread actions menu button not found');
threeDotBtn.focus();
simulateClick(threeDotBtn);
await new Promise(r => setTimeout(r, 500));
let menuItem = Array.from(document.querySelectorAll('[role="menuitem"]'))
.find(m => /export\s*(as\s*)?markdown/i.test(m.textContent));
if (!menuItem) {
menuItem = Array.from(document.querySelectorAll('[role="menuitem"]'))
.find(m => /^export$/i.test(m.textContent.trim()));
}
if (!menuItem) {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
throw new Error('Export as Markdown menu item not found');
}
simulateClick(menuItem);
await new Promise(r => setTimeout(r, 300));
// If clicking "Export" opened a sub-menu, look for "Markdown" item
if (!comm.textContent) {
const mdItem = Array.from(document.querySelectorAll('[role="menuitem"]'))
.find(m => /markdown/i.test(m.textContent) && !/export\s+as/i.test(m.textContent));
if (mdItem) {
simulateClick(mdItem);
await new Promise(r => setTimeout(r, 300));
}
}
// Wait for capture
for (let i = 0; i < 30; i++) {
await new Promise(r => setTimeout(r, 100));
if (comm.textContent) break;
}
return comm.textContent || null;
} finally {
// Restore originals in page context
const cleanup = document.createElement('script');
cleanup.textContent = 'if(window.__pplxport_cleanup)window.__pplxport_cleanup();';
document.documentElement.appendChild(cleanup);
cleanup.remove();
comm.remove();
}
}
function reformatThreadExportMarkdown(rawMd, citationStyle) {
// Normalize line endings (blobs may use CRLF)
let cleaned = rawMd.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
// Remove the Perplexity logo <img> tag and any other HTML img tags
cleaned = cleaned.replace(/<img[^>]*>/gi, '');
// Remove <span style="display:none">...</span> blocks (hidden unused citations)
cleaned = cleaned.replace(/<span\s+style\s*=\s*"display:\s*none"[^>]*>[\s\S]*?<\/span>/gi, '');
// Remove <div align="center">...</div> dividers (the ⁂ separators)
cleaned = cleaned.replace(/<div\s+align\s*=\s*"center"[^>]*>[\s\S]*?<\/div>/gi, '');
// Remove any remaining HTML tags
cleaned = cleaned.replace(/<[^>]+>/g, '');
// Split into Q&A sections by --- horizontal rules
const sections = cleaned.split(/\n---\n/).map(s => s.trim()).filter(s => s.length > 0);
const conversation = [];
for (const section of sections) {
// Each section starts with # question heading, followed by answer body,
// then footnotes like [^N_M]: url at the bottom
const lines = section.split('\n');
let questionText = '';
const answerLines = [];
const footnoteMap = new Map(); // "N_M" -> url
let inFootnotes = false;
for (const line of lines) {
// Check for question heading
const questionMatch = line.match(/^# (.+)$/);
if (questionMatch && !questionText) {
questionText = questionMatch[1].trim();
continue;
}
// Check for per-answer footnote definitions: [^N_M]: url
const footnoteMatch = line.match(/^\[\^(\d+_\d+)\]:\s*(.+)$/);
if (footnoteMatch) {
inFootnotes = true;
footnoteMap.set(footnoteMatch[1], footnoteMatch[2].trim());
continue;
}
// Skip blank lines that appear between footnotes
if (inFootnotes && line.trim() === '') continue;
// If we were in footnotes but hit a non-footnote non-blank line,
// we're back in content (shouldn't normally happen)
if (inFootnotes && line.trim() !== '') {
inFootnotes = false;
}
// Accumulate answer body lines
if (questionText) {
answerLines.push(line);
}
}
if (!questionText) continue;
// Join answer lines and clean up
let answerBody = answerLines.join('\n').trim();
// Normalize horizontal rules within answers to ***
answerBody = answerBody.replace(/^---$/gm, '***');
// Collect which footnote keys are actually referenced in the visible answer body
const referencedKeys = new Set();
for (const m of answerBody.matchAll(/\[\^(\d+_\d+)\]/g)) {
referencedKeys.add(m[1]);
}
// Register only referenced footnotes with globalCitations
const localToGlobalMap = new Map();
for (const [localKey, url] of footnoteMap) {
if (!referencedKeys.has(localKey)) continue;
const globalNum = globalCitations.addCitation(url);
localToGlobalMap.set(localKey, globalNum);
}
// Replace scoped [^N_M] citations in the answer body according to citationStyle
if (citationStyle === CITATION_STYLES.NONE) {
answerBody = answerBody.replace(/\[\^\d+_\d+\]/g, '');
} else {
// Replace runs of consecutive citations like [^1_1][^1_2][^1_3]
answerBody = answerBody.replace(/(?:\[\^\d+_\d+\])+/g, (run) => {
const keys = Array.from(run.matchAll(/\[\^(\d+_\d+)\]/g)).map(m => m[1]);
if (keys.length === 0) return run;
return keys.map(localKey => {
const globalNum = localToGlobalMap.get(localKey) || localKey;
const url = footnoteMap.get(localKey) || '';
switch (citationStyle) {
case CITATION_STYLES.ENDNOTES:
return `[${globalNum}]`;
case CITATION_STYLES.FOOTNOTES:
return `[^${globalNum}]`;
case CITATION_STYLES.INLINE:
return url ? `[${globalNum}](${url})` : `[${globalNum}]`;
case CITATION_STYLES.PARENTHESIZED:
return url ? `([${globalNum}](${url}))` : `([${globalNum}])`;
case CITATION_STYLES.NAMED: {
const domain = extractDomainName(url) || 'source';
return url ? `([${domain}](${url}))` : `([${domain}])`;
}
default:
return `[^${globalNum}]`;
}
}).join('');
});
}
// Clean up excessive whitespace
answerBody = answerBody.replace(/\n{3,}/g, '\n\n').trim();
// Add to conversation
conversation.push({ role: 'User', content: questionText });
conversation.push({ role: 'Assistant', content: answerBody });
}
return conversation;
}
async function extractByThreadExport(citationStyle) {
try {
const rawMd = await interceptThreadExportMarkdown();
if (!rawMd) {
console.log('Thread export: failed to capture markdown');
return [];
}
console.log('Thread export: captured raw markdown, reformatting...');
const conversation = reformatThreadExportMarkdown(rawMd, citationStyle);
console.log(`Thread export: produced ${conversation.length} items`);
return conversation;
} catch (e) {
console.warn('Thread export failed:', e);
return [];
}
}
function reformatDeepResearchMarkdown(rawMd, citationStyle, { appendCitations = true } = {}) {
// Split off the References section
const refSplitPattern = /\n---\s*\n+## References\s*\n|(?:^|\n)## References\s*\n/;
const parts = rawMd.split(refSplitPattern);
let body = parts[0];
const refsBlock = parts.length > 1 ? parts[1] : '';
// Build citation number -> URL map from references section or DOM
// Format: "N. [Title](URL) - Description..."
const citationUrlMap = new Map(); // number string -> { url, title }
if (refsBlock) {
const refLines = refsBlock.split('\n');
for (const line of refLines) {
const match = line.match(/^(\d+)\.\s+\[([^\]]*)\]\(([^)]+)\)/);
if (match) {
citationUrlMap.set(match[1], { title: match[2], url: match[3] });
}
}
}
// Fallback: scrape citation URLs from DOM (for "Copy contents" path which lacks ## References)
if (citationUrlMap.size === 0) {
const citationEls = document.querySelectorAll('[data-pplx-citation-url]');
let num = 0;
const seen = new Set();
for (const el of citationEls) {
const url = el.getAttribute('data-pplx-citation-url');
if (!url || seen.has(url)) continue;
seen.add(url);
num++;
const title = el.textContent.trim() || '';
citationUrlMap.set(String(num), { url, title });
}
}
// Register all references with globalCitations for consistent numbering
const localToGlobalMap = new Map(); // local ref number -> global citation number
for (const [localNum, { url }] of citationUrlMap) {
const globalNum = globalCitations.addCitation(url);
localToGlobalMap.set(localNum, globalNum);
}
// Replace [^N] or [N] citations according to citationStyle
// "Copy contents" produces [N], "Download as Markdown" produces [^N]
const hasCaret = /\[\^\d+\]/.test(body);
const citationRunPattern = hasCaret ? /(?:\[\^\d+\])+/g : /(?:\[\d+\])+/g;
const citationSinglePattern = hasCaret ? /\[\^(\d+)\]/g : /\[(\d+)\]/g;
const citationStripPattern = hasCaret ? /\[\^\d+\]/g : /\[\d+\]/g;
if (citationStyle === CITATION_STYLES.NONE) {
body = body.replace(citationStripPattern, '');
} else {
body = body.replace(citationRunPattern, (run) => {
const nums = Array.from(run.matchAll(citationSinglePattern)).map(m => m[1]);
if (nums.length === 0) return run;
return nums.map(localNum => {
const globalNum = localToGlobalMap.get(localNum) || localNum;
const ref = citationUrlMap.get(localNum);
const url = ref?.url || '';
switch (citationStyle) {
case CITATION_STYLES.ENDNOTES:
return `[${globalNum}]`;
case CITATION_STYLES.FOOTNOTES:
return `[^${globalNum}]`;
case CITATION_STYLES.INLINE:
return url ? `[${globalNum}](${url})` : `[${globalNum}]`;
case CITATION_STYLES.PARENTHESIZED:
return url ? `([${globalNum}](${url}))` : `([${globalNum}])`;
case CITATION_STYLES.NAMED: {
const domain = extractDomainName(url) || 'source';
return url ? `([${domain}](${url}))` : `([${domain}])`;
}
default:
return `[^${globalNum}]`;
}
}).join('');
});
// Remove space between punctuation and citation markers
body = body.replace(/(\.) (\[\^?\d+\])/g, '$1$2');