-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
1616 lines (1353 loc) · 44.9 KB
/
contentScript.js
File metadata and controls
1616 lines (1353 loc) · 44.9 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
// Settings and state management
let currentSettings = {
autoDetection: true,
hideComments: true,
scrollNavigation: true,
videoControls: true,
tikTokSidebar: true, // New setting for TikTok-style sidebar
lastScreenMode: "landscape",
commentOverride: null, // null = no override, true = force hide, false = force show
}
let scrollTimeout = null
let isScrolling = false
let lastScrollTime = 0
let resizeTimeout = null
const SCROLL_DELAY = 150
const RESIZE_DELAY = 300
// Video controls specific variables
const knownVideoElements = new Set()
let videoObserver = null
// TikTok sidebar specific variables
let sidebarElement = null
let sidebarObserver = null
// Initialize extension
initializeExtension()
function initializeExtension() {
loadSettings(() => {
handleUrlChange()
setupScreenDetection()
// Only initialize features if we're in a post modal
if (isInPostModal()) {
addScrollListeners()
if (currentSettings.tikTokSidebar) {
// Add extra delay for initial load
setTimeout(() => {
initializeTikTokSidebar()
}, 1500)
}
}
startObserving()
// Initialize video controls if enabled
if (currentSettings.videoControls) {
initializeVideoControls()
}
})
}
function loadSettings(callback) {
const defaultSettings = {
autoDetection: true,
hideComments: true,
scrollNavigation: true,
videoControls: true,
tikTokSidebar: true,
lastScreenMode: "landscape",
commentOverride: null,
}
chrome.storage.local.get(defaultSettings, settings => {
currentSettings = { ...settings }
if (callback) callback()
})
}
function saveSettings(updates) {
currentSettings = { ...currentSettings, ...updates }
chrome.storage.local.set(updates)
}
// TikTok-Style Sidebar Functionality
function initializeTikTokSidebar() {
if (!currentSettings.tikTokSidebar || !isInPostModal()) return
// Remove existing sidebar if present
removeTikTokSidebar()
// Reset username tracking for fresh start
lastSetUsername = null
// Create and inject the sidebar
createTikTokSidebar()
// Setup observer to update sidebar content
setupSidebarObserver()
}
function createTikTokSidebar() {
// Create sidebar container
sidebarElement = document.createElement("div")
sidebarElement.id = "ig-enhancer-tiktok-sidebar"
sidebarElement.innerHTML = `
<div class="sidebar-item user-profile">
<div class="avatar-container">
<a href="" class="user-link">
<img class="user-avatar" src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMjAiIGN5PSIyMCIgcj0iMjAiIGZpbGw9IiNkYmRiZGIiLz4KPGF0aCBkPSJNMjAgMTBjLTUuNTIzIDAtMTAgNC40NzctMTAgMTBzNC40NzcgMTAgMTAgMTAgMTAtNC40NzcgMTAtMTAtNC40NzctMTAtMTAtMTB6bTAgNmMxLjY1NyAwIDMgMS4zNDMgMyAzcy0xLjM0MyAzLTMgMy0zLTEuMzQzLTMtM3MxLjM0My0zIDMtM3ptMCA4YzIuNzYxIDAgNS0yLjIzOSA1LTV2LTFjLTEuNzA2IDEuMjI0LTMuNzg0IDItNiAycy00LjI5NC0uNzc2LTYtMnYxYzAgMi43NjEgMi4yMzkgNSA1IDV6IiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K" alt="User Avatar">
</a>
</div>
</div>
<div class="sidebar-item like-section">
<button class="action-btn like-btn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M16.792 3.904A4.989 4.989 0 0 1 21.5 9.122c0 3.072-2.652 4.959-5.197 7.222-2.512 2.243-3.865 3.469-4.303 3.752-.477-.309-2.143-1.823-4.303-3.752C5.141 14.072 2.5 12.167 2.5 9.122a4.989 4.989 0 0 1 4.708-5.218 4.21 4.21 0 0 1 3.675 1.941c.84 1.175.98 1.763 1.12 1.763s.278-.588 1.11-1.766a4.17 4.17 0 0 1 3.679-1.938m0-2a6.04 6.04 0 0 0-4.797 2.127 6.052 6.052 0 0 0-4.787-2.127A6.985 6.985 0 0 0 .5 9.122c0 3.61 2.55 5.827 5.015 7.97.283.246.569.494.853.747l1.027.918a44.998 44.998 0 0 0 3.518 3.018 2 2 0 0 0 2.174 0 45.263 45.263 0 0 0 3.626-3.115l.922-.824c.293-.26.59-.519.885-.774 2.334-2.025 4.98-4.32 4.98-7.94a6.985 6.985 0 0 0-6.708-7.218Z" stroke="currentColor" stroke-width="1.5"/>
</svg>
</button>
<div class="count like-count">0</div>
</div>
<div class="sidebar-item comment-section">
<button class="action-btn comment-btn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<path d="M20.656 17.008a9.993 9.993 0 1 0-3.59 3.615L22 22Z" stroke="currentColor" stroke-width="1.5"/>
</svg>
</button>
</div>
<div class="sidebar-item share-section">
<button class="action-btn share-btn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none">
<line x1="22" x2="9.218" y1="3" y2="10.083" stroke="currentColor" stroke-width="1.5"/>
<polygon points="11.698 20.334 22 3.001 2 3.001 9.218 10.084 11.698 20.334" stroke="currentColor" stroke-width="1.5"/>
</svg>
</button>
</div>
`
// Add CSS styles
addTikTokSidebarCSS()
// Add event listeners
setupSidebarEventListeners()
// Extract and populate data
populateSidebarData()
// Find the navigation container and inject sidebar
const navContainer = findNavigationContainer()
if (navContainer) {
navContainer.appendChild(sidebarElement)
} else {
// Fallback to body if navigation container not found
document.body.appendChild(sidebarElement)
}
}
function findNavigationContainer() {
// Try to find navigation container by looking for navigation buttons
const navButtons = document.querySelectorAll('button[type="button"]')
for (const button of navButtons) {
const svg = button.querySelector("svg")
if (svg) {
const ariaLabel = svg.getAttribute("aria-label")
const title = svg.querySelector("title")?.textContent
if (ariaLabel === "Next" || title === "Next") {
// Found the next button, return body for fixed positioning
return document.body
}
}
}
// Fallback to body
return document.body
}
function formatCount(countStr) {
const count = parseInt(countStr.replace(/[^\d]/g, "")) || 0
if (count >= 1000000) {
return (count / 1000000).toFixed(1).replace(".0", "") + "M"
} else if (count >= 1000) {
return (count / 1000).toFixed(1).replace(".0", "") + "K"
}
return count.toString()
}
function addTikTokSidebarCSS() {
const styleId = "ig-enhancer-tiktok-sidebar-styles"
if (document.getElementById(styleId)) return
const style = document.createElement("style")
style.id = styleId
style.textContent = `
#ig-enhancer-tiktok-sidebar {
position: fixed;
right: 5px;
top: 60%;
transform: translateY(-50%);
z-index: 1000;
display: flex;
flex-direction: column;
gap: 12px;
background: rgba(0, 0, 0, 0.05);
backdrop-filter: blur(8px);
border-radius: 8px;
padding: 8px 5px;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
width: 44px;
}
/* Position adjustment based on screen orientation */
@media (orientation: portrait) {
#ig-enhancer-tiktok-sidebar {
top: 62%;
}
}
@media (orientation: landscape) {
#ig-enhancer-tiktok-sidebar {
top: 70%;
}
}
#ig-enhancer-tiktok-sidebar:hover {
background: rgba(0, 0, 0, 0.1);
border-color: rgba(255, 255, 255, 0.2);
}
.sidebar-item {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.user-profile {
cursor: pointer;
transition: transform 0.2s ease;
}
.user-profile:hover {
transform: scale(1.1);
}
.avatar-container {
width: 36px;
height: 36px;
border-radius: 50%;
overflow: hidden;
border: 2px solid rgba(255, 255, 255, 0.3);
transition: border-color 0.2s ease;
}
.user-profile:hover .avatar-container {
border-color: rgba(255, 255, 255, 0.8);
}
.user-link {
display: block;
width: 100%;
height: 100%;
text-decoration: none;
}
.user-avatar {
width: 100%;
height: 100%;
object-fit: cover;
}
.action-btn {
width: 36px;
height: 36px;
border: none;
border-radius: 50%;
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(5px);
color: white;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.action-btn:hover {
background: rgba(255, 255, 255, 0.2);
transform: scale(1.1);
border-color: rgba(255, 255, 255, 0.4);
}
.action-btn:active {
transform: scale(0.95);
}
#ig-enhancer-tiktok-sidebar .sidebar-item .action-btn.like-btn.liked {
background: #ed4956 !important;
color: #ffffff !important;
border-color: #ed4956 !important;
border: 2px solid #ed4956 !important;
}
#ig-enhancer-tiktok-sidebar .sidebar-item .action-btn.like-btn.liked:hover {
background: #c73650 !important;
border-color: #c73650 !important;
}
#ig-enhancer-tiktok-sidebar .sidebar-item .action-btn.like-btn.liked svg {
color: #ffffff !important;
}
#ig-enhancer-tiktok-sidebar .sidebar-item .action-btn.like-btn.liked svg path {
fill: #ffffff !important;
stroke: #ffffff !important;
}
/* Debug - this should make ANY liked button have a yellow border */
.like-btn.liked {
border: 3px solid yellow !important;
}
.count {
font-size: 10px;
color: white;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.7);
font-weight: 600;
text-align: center;
min-width: 36px;
background: rgba(0, 0, 0, 0.3);
border-radius: 10px;
padding: 2px 4px;
line-height: 1.2;
}
/* Responsive adjustments */
@media (max-width: 768px) {
#ig-enhancer-tiktok-sidebar {
right: 12px;
gap: 10px;
padding: 6px;
width: 40px;
}
.avatar-container {
width: 32px;
height: 32px;
}
.action-btn {
width: 32px;
height: 32px;
}
.action-btn svg {
width: 16px;
height: 16px;
}
.count {
font-size: 9px;
min-width: 32px;
}
}
/* Hide when comments are shown to avoid overlap */
.ig-enhancer-sidebar-hidden {
opacity: 0;
pointer-events: none;
transform: translateY(-50%) translateX(20px);
}
`
document.head.appendChild(style)
}
function setupSidebarEventListeners() {
if (!sidebarElement) return
// User profile click - just handle left clicks to prevent default
const userLink = sidebarElement.querySelector(".user-link")
userLink.addEventListener("click", handleUserProfileClick)
// Like button click
const likeBtn = sidebarElement.querySelector(".like-btn")
likeBtn.addEventListener("click", handleLikeClick)
// Comment button click
const commentBtn = sidebarElement.querySelector(".comment-btn")
commentBtn.addEventListener("click", handleCommentToggle)
// Share button click
const shareBtn = sidebarElement.querySelector(".share-btn")
shareBtn.addEventListener("click", handleShareClick)
}
// Add a flag to prevent infinite loops
let isUpdatingSidebar = false
let sidebarUpdateTimeout = null
let lastSetUsername = null // Track the last username we set to avoid unnecessary updates
function extractLikeCount() {
let likeCount = "0"
try {
// Method 1: Find the "liked_by" link (most reliable for "X others" format)
const likedByLink = document.querySelector('a[href*="/liked_by/"]')
if (likedByLink) {
// Get all text content and look for number + "others"
const linkText = likedByLink.textContent.trim()
// Match "X others" pattern (when someone you follow liked it)
const othersMatch = linkText.match(/([\d,]+)\s+others/i)
if (othersMatch) {
likeCount = othersMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in 'others' format:",
likeCount
)
return likeCount
}
// Match simple "X likes" pattern
const likesMatch = linkText.match(/([\d,]+)\s+likes?/i)
if (likesMatch) {
likeCount = likesMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in 'likes' format:",
likeCount
)
return likeCount
}
}
// Method 2: Look specifically for the number in span.html-span (for complex structure)
const numberSpan = document.querySelector(
'a[href*="/liked_by/"] span.html-span'
)
if (numberSpan) {
const numberText = numberSpan.textContent.trim()
const numberMatch = numberText.match(/^([\d,]+)$/)
if (numberMatch) {
likeCount = numberMatch[1].replace(/,/g, "")
console.log("IG Enhancer: Found like count in html-span:", likeCount)
return likeCount
}
}
// Method 3: Backup - look for any span containing number + "others"
const spans = document.querySelectorAll("span")
for (const span of spans) {
const text = span.textContent.trim()
// Look for "X others" pattern
const othersMatch = text.match(/^([\d,]+)\s+others$/i)
if (othersMatch) {
likeCount = othersMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in span 'others' format:",
likeCount
)
return likeCount
}
// Look for "X likes" pattern
const likesMatch = text.match(/^([\d,]+)\s+likes?$/i)
if (likesMatch) {
likeCount = likesMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in span 'likes' format:",
likeCount
)
return likeCount
}
}
// Method 4: Look for the specific structure when someone you follow liked it
// Find elements containing "others" and extract the number before it
const othersElements = document.querySelectorAll("*")
for (const element of othersElements) {
const text = element.textContent
if (text && text.includes(" others")) {
// Look for "Liked by username and X others" pattern
const complexMatch = text.match(/and\s+([\d,]+)\s+others/i)
if (complexMatch) {
likeCount = complexMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in complex 'and X others' format:",
likeCount
)
return likeCount
}
// Look for simple "X others" pattern
const simpleMatch = text.match(/([\d,]+)\s+others/i)
if (simpleMatch) {
likeCount = simpleMatch[1].replace(/,/g, "")
console.log(
"IG Enhancer: Found like count in 'others' format:",
likeCount
)
return likeCount
}
}
}
console.log("IG Enhancer: No like count found, defaulting to 0")
return "0"
} catch (error) {
console.log("IG Enhancer: Error extracting like count:", error)
return "0"
}
}
function detectPageType() {
const urlPath = window.location.pathname
// User profile page: /username/ or /username/p/postid/
// Check if URL starts with /username/ (not /p/, /explore/, /reels/, etc.)
const profileMatch = urlPath.match(/^\/([^\/]+)\/?/)
if (profileMatch) {
const segment = profileMatch[1]
// Exclude known non-user paths
const nonUserPaths = [
"p",
"explore",
"reels",
"tv",
"stories",
"accounts",
"direct",
]
if (!nonUserPaths.includes(segment)) {
return {
type: "profile",
username: segment,
}
}
}
// Explore page
if (urlPath.includes("/explore/")) {
return { type: "explore" }
}
// Individual post (not from profile)
if (urlPath.includes("/p/")) {
return { type: "post" }
}
// Home feed or other
return { type: "feed" }
}
function populateSidebarData() {
if (!sidebarElement || isUpdatingSidebar) return
// Debounce rapid calls
if (sidebarUpdateTimeout) {
clearTimeout(sidebarUpdateTimeout)
}
sidebarUpdateTimeout = setTimeout(() => {
try {
isUpdatingSidebar = true // Prevent recursive calls
// Detect what type of page we're on
const pageInfo = detectPageType()
// Extract username and avatar from the header
const dialog = document.querySelector('div[role="dialog"]')
const headerScope = dialog
? dialog.querySelector("header")
: document.querySelector("main header")
const userAvatar = headerScope?.querySelector(
'img[alt$="\'s profile picture"]'
)
if (userAvatar) {
const avatarSrc = userAvatar.src
const username = userAvatar.alt.replace(/'s profile picture$/, "")
// Smart avatar updating logic
let shouldUpdateAvatar = false
if (pageInfo.type === "profile") {
// On profile pages, only update avatar if username actually changed or first time
if (!lastSetUsername || lastSetUsername !== username) {
shouldUpdateAvatar = true
console.log(
`IG Enhancer: Profile page - updating avatar for user: ${username}`
)
}
// Don't update avatar for same user on profile page
} else {
// On explore/feed pages, always update avatar as each post might be from different users
if (lastSetUsername !== username) {
shouldUpdateAvatar = true
console.log(
`IG Enhancer: ${pageInfo.type} page - updating avatar for user: ${username}`
)
}
}
if (shouldUpdateAvatar) {
const avatarImg = sidebarElement.querySelector(".user-avatar")
const userLink = sidebarElement.querySelector(".user-link")
avatarImg.src = avatarSrc
userLink.href = `/${username}/`
sidebarElement.dataset.username = username
lastSetUsername = username
}
}
// Always update like count (this should work on all page types)
const likeCount = extractLikeCount()
const likeCountElement = sidebarElement.querySelector(".like-count")
const formattedLikeCount = formatCount(likeCount)
if (likeCountElement.textContent !== formattedLikeCount) {
likeCountElement.textContent = formattedLikeCount
}
// Always check if post is already liked (this should work on all page types)
const postModal = document.querySelector('article[role="presentation"]')
const section = postModal?.querySelector("section")
const likeBtn = sidebarElement.querySelector(".like-btn")
if (section && likeBtn) {
// Check for "Unlike" svg to determine if post is already liked
const isLiked =
section.querySelector('svg[aria-label="Unlike"][height="24"]') !==
null
// Only update if state has actually changed
const currentlyLiked = likeBtn.classList.contains("liked")
if (isLiked && !currentlyLiked) {
likeBtn.classList.add("liked")
likeBtn.style.backgroundColor = "#ed4956"
likeBtn.style.borderColor = "#ed4956"
console.log(
"IG Enhancer: Applied liked state to sidebar button for already-liked post"
)
} else if (!isLiked && currentlyLiked) {
likeBtn.classList.remove("liked")
likeBtn.style.backgroundColor = ""
likeBtn.style.borderColor = ""
console.log("IG Enhancer: Applied unliked state to sidebar button")
}
// If state hasn't changed, don't log anything
}
} catch (error) {
console.log("IG Enhancer: Error populating sidebar data:", error)
} finally {
isUpdatingSidebar = false // Always reset the flag
}
}, 200) // 200ms debounce
}
function handleUserProfileClick(event) {
// Only prevent default for regular left clicks (no modifiers)
if (
event.button === 0 &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey
) {
event.preventDefault()
event.stopPropagation()
window.location.href = event.target.closest(".user-link").href
}
// Let middle-click and ctrl+click open in new tab, let right-click show context menu
}
function handleLikeClick(event) {
event.preventDefault()
event.stopPropagation()
try {
if (!sidebarElement) return
const postModal = document.querySelector('article[role="presentation"]')
if (!postModal) return
const section = postModal.querySelector("section")
if (!section) return
let likeButton = null
// Look for like/unlike button using more stable selectors
const likeSvg = section.querySelector('svg[aria-label="Like"][height="24"]')
const unlikeSvg = section.querySelector(
'svg[aria-label="Unlike"][height="24"]'
)
const targetSvg = likeSvg || unlikeSvg
if (targetSvg) {
// Find the clickable parent element (div[role="button"])
let element = targetSvg.parentElement
while (element && element !== section) {
if (element.getAttribute("role") === "button") {
likeButton = element
break
}
element = element.parentElement
}
}
if (likeButton) {
// Click the actual Instagram like button
likeButton.click()
// Wait and check the state
setTimeout(() => {
if (!sidebarElement) return
const updatedPostModal = document.querySelector(
'article[role="presentation"]'
)
const updatedSection = updatedPostModal?.querySelector("section")
if (updatedSection) {
// Check current state by aria-label
const isLiked =
updatedSection.querySelector(
'svg[aria-label="Unlike"][height="24"]'
) !== null
// Update sidebar like button appearance
const sidebarLikeBtn = sidebarElement.querySelector(".like-btn")
if (sidebarLikeBtn) {
if (isLiked) {
sidebarLikeBtn.classList.add("liked")
sidebarLikeBtn.style.backgroundColor = "#ed4956"
sidebarLikeBtn.style.borderColor = "#ed4956"
} else {
sidebarLikeBtn.classList.remove("liked")
sidebarLikeBtn.style.backgroundColor = ""
sidebarLikeBtn.style.borderColor = ""
}
}
}
// Update the like count
populateSidebarData()
}, 1000)
}
} catch (error) {
console.log("IG Enhancer: Error handling like click:", error)
}
}
function handleCommentToggle(event) {
event.preventDefault()
event.stopPropagation()
// Toggle comments visibility using existing functionality
const shouldHide = !getShouldHideComments()
// Update override to toggle comments
currentSettings.commentOverride = shouldHide
saveSettings({ commentOverride: shouldHide })
// Apply the change
updateCommentsVisibility(shouldHide)
// Update sidebar visibility
updateSidebarVisibility()
}
function handleShareClick(event) {
event.preventDefault()
event.stopPropagation()
try {
// Find the share button in the section
const section = document.querySelector("section")
if (section) {
const buttons = section.querySelectorAll("button")
// Share button is typically the third button (like, comment, share)
const shareButton = buttons[2]
if (shareButton) {
shareButton.click()
}
}
} catch (error) {
console.log("IG Enhancer: Error handling share click:", error)
}
}
function updateSidebarVisibility() {
if (!sidebarElement) return
const commentsVisible = !getShouldHideComments()
if (commentsVisible) {
sidebarElement.classList.add("ig-enhancer-sidebar-hidden")
} else {
sidebarElement.classList.remove("ig-enhancer-sidebar-hidden")
}
}
function setupSidebarObserver() {
// Update sidebar on content changes
if (sidebarObserver) return
sidebarObserver = new MutationObserver(mutations => {
let shouldUpdate = false
mutations.forEach(mutation => {
if (
mutation.target.id === "ig-enhancer-tiktok-sidebar" ||
mutation.target.closest("#ig-enhancer-tiktok-sidebar")
) {
return
}
if (
mutation.target.matches &&
(mutation.target.matches("section") ||
mutation.target.closest("section")) &&
!mutation.target.closest("#ig-enhancer-tiktok-sidebar")
) {
if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
shouldUpdate = true
} else if (
mutation.type === "attributes" &&
(mutation.attributeName === "aria-label" ||
mutation.attributeName === "fill")
) {
shouldUpdate = true
}
}
})
if (shouldUpdate && sidebarElement && !isUpdatingSidebar) {
// Debounce updates
clearTimeout(window.sidebarUpdateTimeout)
window.sidebarUpdateTimeout = setTimeout(() => {
populateSidebarData()
}, 500) // Increased debounce time
}
})
sidebarObserver.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["aria-label", "fill"], // Only watch for specific attribute changes
})
}
function removeTikTokSidebar() {
if (sidebarElement) {
sidebarElement.remove()
sidebarElement = null
}
if (sidebarObserver) {
sidebarObserver.disconnect()
sidebarObserver = null
}
// Reset the username tracking when sidebar is removed
lastSetUsername = null
// Remove styles
const styles = document.getElementById("ig-enhancer-tiktok-sidebar-styles")
if (styles) {
styles.remove()
}
}
// Screen detection functionality
function setupScreenDetection() {
if (currentSettings.autoDetection) {
detectScreenMode()
window.addEventListener("resize", handleResize)
// Also listen for screen orientation changes
window.addEventListener("orientationchange", handleResize)
// And for when window moves between screens
window.addEventListener("focus", handleResize)
} else {
window.removeEventListener("resize", handleResize)
window.removeEventListener("orientationchange", handleResize)
window.removeEventListener("focus", handleResize)
}
}
function handleResize() {
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeTimeout = setTimeout(() => {
if (currentSettings.autoDetection) {
detectScreenMode()
}
}, RESIZE_DELAY)
}
function detectScreenMode() {
const width = window.innerWidth
const height = window.innerHeight
const aspectRatio = width / height
// Consider portrait if aspect ratio is less than 1.2 (to account for tablets)
const isPortrait = aspectRatio < 1.2
const newScreenMode = isPortrait ? "portrait" : "landscape"
// Always update settings and send status update, even if mode hasn't changed
// This ensures the popup shows the correct current state
currentSettings.lastScreenMode = newScreenMode
saveSettings({ lastScreenMode: newScreenMode })
if (currentSettings.autoDetection) {
// Only clear override when screen mode actually changes and we're switching
// to a mode that would naturally match what the override was doing
if (currentSettings.commentOverride !== null) {
const autoWouldHide = isPortrait
if (currentSettings.commentOverride === autoWouldHide) {
// Override matches what auto detection would do, so clear it
currentSettings.commentOverride = null
saveSettings({ commentOverride: null })
}
}
// Apply comment visibility based on current state
const shouldHideComments = getShouldHideComments()
updateCommentsVisibility(shouldHideComments)
}
// Update sidebar visibility
if (currentSettings.tikTokSidebar) {
updateSidebarVisibility()
}
// Always send status update to popup to ensure it's current
sendStatusUpdate()
}
function getShouldHideComments() {
if (currentSettings.commentOverride !== null) {
// Override takes precedence
return currentSettings.commentOverride
}
if (currentSettings.autoDetection) {
// Auto detection: hide in portrait, show in landscape
return currentSettings.lastScreenMode === "portrait"
} else {
// Manual mode
return currentSettings.hideComments
}
}
function updateCommentsVisibility(hide) {
const styleId = "hide-comments-style"
let styleElement = document.getElementById(styleId)
if (hide) {
if (!styleElement) {
styleElement = document.createElement("style")
styleElement.id = styleId
styleElement.innerText = `
article[role="presentation"] > div > div:nth-child(2) {
display: none !important;
}
`
document.head.appendChild(styleElement)
}
} else {
if (styleElement) {
styleElement.remove()
}
}
// Update sidebar visibility when comments visibility changes
if (currentSettings.tikTokSidebar) {
updateSidebarVisibility()
}
}
function shouldHideComments() {
return getShouldHideComments()
}
// Scroll navigation functionality (preserved from original)
function findNavigationButtons() {
const navButtons = document.querySelectorAll('button[type="button"]')
let prevButton = null
let nextButton = null
navButtons.forEach(button => {
const svg = button.querySelector("svg")