-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
268 lines (227 loc) · 8.58 KB
/
Copy pathcontentScript.js
File metadata and controls
268 lines (227 loc) · 8.58 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
// == LinkedIn LLM Sniffer v2 =============================================
// Detects likely AI‑generated posts and requests a reverse prompt
// from the background service worker.
// ========================================================================
/**
* Debug logging function
*/
function debugLog(message, data = null) {
const timestamp = new Date().toISOString();
const logMessage = `[DearLLM Content] ${timestamp}: ${message}`;
console.log(logMessage, data || '');
}
/* Heuristic detector (same idea as before) */
function looksLikeAI(text) {
if (!text) {
debugLog('Empty text provided to looksLikeAI');
return false;
}
const wordCount = text.split(/\s+/).length;
debugLog('Analyzing text for AI patterns', {
wordCount,
textLength: text.length,
textPreview: text.substring(0, 100) + (text.length > 100 ? '...' : '')
});
if (wordCount > 120) {
debugLog('Text flagged as AI due to word count', { wordCount });
return true;
}
const tropes = [
/here (?:are|is) \d+/i,
/\bleverage\b/i,
/\bsynergy\b/i,
/\bthrilled to announce\b/i
];
const matchedTropes = tropes.filter(rx => rx.test(text));
if (matchedTropes.length > 0) {
debugLog('Text flagged as AI due to matched tropes', {
matchedTropes: matchedTropes.map(rx => rx.source),
wordCount
});
return true;
}
debugLog('Text does not appear to be AI-generated', { wordCount });
return false;
}
/* Build the banner once we have the LLM prompt */
function buildBanner(prompt) {
debugLog('Building banner with prompt', { promptLength: prompt.length });
const el = document.createElement("div");
el.style.cssText = `
font-weight: 700;
margin-bottom: 6px;
line-height: 1.3;
background-color: #ffffe8;
padding: 10px;
border-radius: 10px;
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
margin: 5px 2px 15px;
font-family: 'Courier New', monospace;
`;
el.setAttribute("data-llm-tagged", "true");
debugLog('Banner element created', {
hasDataAttribute: el.hasAttribute('data-llm-tagged')
});
return el;
}
/* Typewriter effect function */
function typewriterEffect(element, text, speed = 10) { // 50ms = 20 chars per second
debugLog('Starting typewriter effect', { textLength: text.length, speed });
element.textContent = '';
let index = 0;
function typeNextChar() {
if (index < text.length) {
element.textContent += text[index];
index++;
setTimeout(typeNextChar, speed);
} else {
debugLog('Typewriter effect completed');
}
}
typeNextChar();
}
/* Extract visible text from a LinkedIn post */
function getPostText(post) {
debugLog('Extracting text from post element', {
postTagName: post.tagName,
postClassName: post.className
});
const textElements = post.querySelectorAll('.feed-shared-inline-show-more-text');
const text = [...textElements].map(s => s.innerText).join(" ").trim();
debugLog('Text extracted from post', {
elementCount: textElements.length,
textLength: text.length,
textPreview: text.substring(0, 100) + (text.length > 100 ? '...' : '')
});
return text;
}
/* Send message to background and inject banner */
function processPost(post) {
debugLog('Processing post element', {
postTagName: post.tagName,
postClassName: post.className,
hasExistingTag: !!post.querySelector('[data-llm-tagged]')
});
if (post.querySelector('[data-llm-tagged]')) {
debugLog('Post already processed, skipping');
return;
}
const text = getPostText(post);
if (!looksLikeAI(text)) {
debugLog('Post does not look like AI, skipping');
return;
}
debugLog('Post looks like AI, sending to background script');
chrome.runtime.sendMessage({ action: "reversePrompt", text }, (resp) => {
debugLog('Received response from background script', {
hasPrompt: !!resp?.prompt,
hasError: !!resp?.error,
error: resp?.error
});
const prompt = resp?.prompt;
const error = resp?.error;
const bannerText = prompt && !error
? `${prompt}`
: 'Dear LLM, (could not generate prompt 🤖)';
const banner = buildBanner(bannerText);
debugLog('Injecting banner into first feed-shared-inline-show-more-text element');
const firstTextElement = post.querySelector('.feed-shared-inline-show-more-text');
if (firstTextElement) {
firstTextElement.insertBefore(banner, firstTextElement.firstChild);
debugLog('Banner injected successfully into text element');
// Start typewriter effect
typewriterEffect(banner, bannerText);
// Auto-expand the post if there's a "...more" button
setTimeout(() => {
const moreButton = post.querySelector('button[aria-label*="more"], button[aria-label*="See more"], .artdeco-button[aria-label*="more"]');
if (moreButton) {
debugLog('Found "...more" button, clicking to expand post');
moreButton.click();
document.body.click();
debugLog('Clicked "...more" button');
} else {
debugLog('No "...more" button found in this post');
}
}, 100); // Small delay to ensure banner is rendered first
} else {
debugLog('No feed-shared-inline-show-more-text element found, falling back to post prepend');
post.prepend(banner);
debugLog('Banner injected successfully into post');
// Start typewriter effect for fallback case
typewriterEffect(banner, bannerText);
}
});
}
/* Process post only when it becomes visible */
function processPostWhenVisible(post) {
debugLog('Setting up visibility observer for post');
// Check if post is already visible
const rect = post.getBoundingClientRect();
const isVisible = rect.top < window.innerHeight && rect.bottom > 0;
if (isVisible) {
debugLog('Post is already visible, processing immediately');
processPost(post);
return;
}
// Create intersection observer for visibility
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
debugLog('Post became visible, processing now');
observer.unobserve(entry.target);
processPost(entry.target);
}
});
}, {
threshold: 0.1, // Trigger when 10% of the post is visible
rootMargin: '50px' // Start loading 50px before the post comes into view
});
observer.observe(post);
debugLog('Visibility observer set up for post');
}
/* MutationObserver: watch feed for new posts */
function start() {
debugLog('Starting content script');
const FEED = document.querySelector('div.scaffold-finite-scroll__content');
if (!FEED) {
debugLog('Feed element not found, retrying in 1 second');
setTimeout(start, 1000);
return;
}
debugLog('Feed element found, setting up observer');
const seen = new WeakSet();
const scan = (root) => {
const posts = root.querySelectorAll('div.feed-shared-update-v2');
debugLog('Scanning for posts', { postCount: posts.length });
posts.forEach((p, index) => {
if (!seen.has(p)) {
debugLog(`Found new post ${index + 1}/${posts.length}`);
seen.add(p);
processPostWhenVisible(p);
}
});
};
scan(FEED);
const observer = new MutationObserver(muts => {
debugLog('Mutation observed', { mutationCount: muts.length });
muts.forEach(m => m.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
debugLog('New element added, scanning');
scan(node);
}
}));
});
observer.observe(FEED, { childList: true, subtree: true });
debugLog('MutationObserver started');
}
document.addEventListener("DOMContentLoaded", () => {
debugLog('DOMContentLoaded event fired, starting content script');
start();
});
// Immediate start attempt for already loaded pages
if (document.readyState === 'loading') {
debugLog('Document still loading, waiting for DOMContentLoaded');
} else {
debugLog('Document already loaded, starting immediately');
start();
}