-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontentScript.js
More file actions
2020 lines (1750 loc) · 80.4 KB
/
contentScript.js
File metadata and controls
2020 lines (1750 loc) · 80.4 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
const offersRootSelectorValue = "bx.catalog.container";
const offersRootSelector = `[elementtiming="${offersRootSelectorValue}"]`;
const offersSelector = '[data-marker="item"]';
const logPrefix = "[ave]";
const sellerPageSidebarSelector = `[class^="ExtendedProfileStickyContainer-"]`;
// Селекторы для раздела рекомендаций на главной странице
const recommendationsItemSelector = '[class*="js-item-"]';
const recommendationsCardSelector = '[data-marker="bx-recommendations-block-item"]';
// Определение главной страницы
function isHomePage() {
const pathname = window.location.pathname;
return pathname === '/' || pathname === '';
}
// ==================== USER PROFILE PAGE FUNCTIONALITY ====================
// Определение страницы профиля пользователя
function isUserProfilePage() {
const pathname = window.location.pathname;
return pathname.includes('/user/') || pathname.includes('/brands/');
}
// Извлечение ID продавца из URL профиля
function getSellerIdFromUrl() {
const pathname = window.location.pathname;
const userMatch = pathname.match(/\/user\/([^\/]+)/);
const brandMatch = pathname.match(/\/brands\/([^\/]+)/);
if (userMatch) return userMatch[1].split('?')[0];
if (brandMatch) return brandMatch[1].split('?')[0];
return null;
}
// ==================== ITEM PAGE FUNCTIONALITY ====================
// Определение страницы товара (item page)
// URL паттерн: /город/категория/название_ID или /город/категория/подкатегория/название_ID
function isItemPage() {
const pathname = window.location.pathname;
// Исключаем служебные страницы
const excludedPaths = ['user', 'brands', 'companies', 'shops', 'profile', 'favorites', 'messages', 'search'];
const pathParts = pathname.split('/').filter(part => part !== '');
// Минимум 3 части: город, категория, название_id
if (pathParts.length < 3) return false;
// Первая часть не должна быть служебной
if (excludedPaths.includes(pathParts[0])) return false;
// Последняя часть должна содержать ID (заканчиваться на _цифры или просто цифры)
const lastPart = pathParts[pathParts.length - 1];
return /[_]\d+$/.test(lastPart) || /^\d+$/.test(lastPart);
}
// Извлечение ID объявления из URL страницы товара
function getItemPageOfferId() {
const pathname = window.location.pathname;
// Ищем ID в конце URL (после последнего _ или как отдельное число)
const match = pathname.match(/_(\d+)(?:\?|$|#)/) || pathname.match(/\/(\d+)(?:\?|$|#)/);
if (match) {
return match[1];
}
// Альтернативный способ - из конца pathname
const parts = pathname.split('/').filter(p => p);
if (parts.length > 0) {
const lastPart = parts[parts.length - 1].split('?')[0];
const idMatch = lastPart.match(/_(\d+)$/) || lastPart.match(/^(\d+)$/);
if (idMatch) {
return idMatch[1];
}
}
return null;
}
// Извлечение ID продавца из DOM на странице товара
function getItemPageSellerId() {
// Ищем ссылку на продавца
const sellerLink = document.querySelector('a[data-marker="seller-link/link"]');
if (sellerLink) {
const href = sellerLink.href;
// Поддерживаем /user/ и /brands/
const userMatch = href.match(/\/user\/([^\/\?]+)/);
const brandMatch = href.match(/\/brands\/([^\/\?]+)/);
if (userMatch) {
return userMatch[1];
} else if (brandMatch) {
return brandMatch[1];
}
}
return null;
}
// Проверка наличия кнопок на странице товара
function hasItemPageButtons() {
return document.querySelector('.item-page-blacklist-container') !== null;
}
// Создание кнопки в стиле Avito
function createItemPageButton(text, isBlock, onClick) {
const button = document.createElement('button');
button.type = 'button';
button.className = isBlock ? 'item-page-block-btn' : 'item-page-unblock-btn';
button.innerHTML = `<span class="item-page-btn-wrapper"><span class="item-page-btn-text">${text}</span></span>`;
button.addEventListener('click', (e) => {
e.stopPropagation();
e.preventDefault();
onClick();
});
return button;
}
// Вставка кнопок на страницу товара
function insertItemPageButtons(offerId, sellerId) {
// Проверяем, не добавлены ли уже кнопки
if (hasItemPageButtons()) {
// Обновляем существующие кнопки
updateItemPageButtons(offerId, sellerId);
return;
}
// Ищем контейнер с кнопками "Показать телефон" и "Написать"
const contactBar = document.querySelector('[class*="contact-bar__root"]') ||
document.querySelector('[class*="style__contactBarOnly"]');
if (!contactBar) {
console.log(`${logPrefix} Контейнер contact-bar не найден на странице товара`);
return;
}
// Создаем контейнер для наших кнопок
const container = document.createElement('div');
container.className = 'item-page-blacklist-container';
// Проверяем состояние в блеклисте
const userIsBlacklisted = sellerId && blacklistUsers.includes(sellerId + "_blacklist_user");
const offerIsBlacklisted = offerId && blacklistOffers.includes(offerId + "_blacklist_ad");
// Кнопка для продавца
if (sellerId) {
const sellerButton = createItemPageButton(
userIsBlacklisted ? 'Разблокировать продавца' : 'Заблокировать продавца',
!userIsBlacklisted,
() => {
if (userIsBlacklisted) {
removeUserFromBlacklist(sellerId);
} else {
addUserToBlacklist(sellerId);
}
updateItemPageButtons(offerId, sellerId);
}
);
container.appendChild(sellerButton);
}
// Кнопка для объявления
if (offerId) {
const offerButton = createItemPageButton(
offerIsBlacklisted ? 'Разблокировать объявление' : 'Заблокировать объявление',
!offerIsBlacklisted,
() => {
if (offerIsBlacklisted) {
removeOfferFromBlacklist(offerId);
} else {
addOfferToBlacklist(offerId);
}
updateItemPageButtons(offerId, sellerId);
}
);
container.appendChild(offerButton);
}
// Вставляем контейнер после основных кнопок
contactBar.appendChild(container);
console.log(`${logPrefix} Кнопки блокировки добавлены на страницу товара`);
}
// Обновление кнопок на странице товара
function updateItemPageButtons(offerId, sellerId) {
const container = document.querySelector('.item-page-blacklist-container');
if (!container) return;
// Удаляем старые кнопки
container.innerHTML = '';
// Проверяем состояние в блеклисте
const userIsBlacklisted = sellerId && blacklistUsers.includes(sellerId + "_blacklist_user");
const offerIsBlacklisted = offerId && blacklistOffers.includes(offerId + "_blacklist_ad");
// Кнопка для продавца
if (sellerId) {
const sellerButton = createItemPageButton(
userIsBlacklisted ? 'Разблокировать продавца' : 'Заблокировать продавца',
!userIsBlacklisted,
() => {
if (userIsBlacklisted) {
removeUserFromBlacklist(sellerId);
} else {
addUserToBlacklist(sellerId);
}
updateItemPageButtons(offerId, sellerId);
}
);
container.appendChild(sellerButton);
}
// Кнопка для объявления
if (offerId) {
const offerButton = createItemPageButton(
offerIsBlacklisted ? 'Разблокировать объявление' : 'Заблокировать объявление',
!offerIsBlacklisted,
() => {
if (offerIsBlacklisted) {
removeOfferFromBlacklist(offerId);
} else {
addOfferToBlacklist(offerId);
}
updateItemPageButtons(offerId, sellerId);
}
);
container.appendChild(offerButton);
}
}
// Основная функция обработки страницы товара
function processItemPage() {
if (!isItemPage()) return;
const offerId = getItemPageOfferId();
const sellerId = getItemPageSellerId();
console.log(`${logPrefix} Страница товара: offerId=${offerId}, sellerId=${sellerId}`);
if (offerId || sellerId) {
insertItemPageButtons(offerId, sellerId);
}
}
// Извлечение ID объявления из класса элемента рекомендаций (js-item-XXXXXXX)
function getRecommendationOfferId(element) {
const classList = element.className;
const match = classList.match(/js-item-(\d+)/);
return match ? match[1] : null;
}
// browser compatibility
if (typeof browser === "undefined") {
var browser = chrome;
}
// STORAGE
function hasNumber(myString) {
return /\d/.test(myString);
}
function syncStore(key, objectToStore) {
var jsonstr = JSON.stringify(objectToStore);
var i = 0;
var storageObj = {};
// split jsonstr into chunks and store them in an object indexed by `key_i`
while (jsonstr.length > 0) {
var index = key + "_" + i++;
// since the key uses up some per-item quota, see how much is left for the value
// also trim off 2 for quotes added by storage-time `stringify`
const maxLength = browser.storage.local.QUOTA_BYTES_PER_ITEM - index.length - 2;
var valueLength = jsonstr.length;
if (valueLength > maxLength) {
valueLength = maxLength;
}
// trim down segment so it will be small enough even when run through `JSON.stringify` again at storage time
//max try is QUOTA_BYTES_PER_ITEM to avoid infinite loop
var segment = jsonstr.substr(0, valueLength);
for (let i = 0; i < browser.storage.local.QUOTA_BYTES_PER_ITEM; i++) {
const jsonLength = JSON.stringify(segment).length;
if (jsonLength > maxLength) {
segment = jsonstr.substr(0, --valueLength);
} else {
break;
}
}
storageObj[index] = segment;
jsonstr = jsonstr.substr(valueLength);
}
browser.storage.local.set(storageObj);
}
function syncGet(key) {
return new Promise((resolve) => {
browser.storage.local.get(null, function (items) {
const keyArr = new Array();
for (let item of Object.keys(items)) {
if (item.includes(key)) {
if (hasNumber(item)) {
keyArr.push(item);
}
}
}
browser.storage.local.get(keyArr, (items) => {
const keys = Object.keys(items);
const length = keys.length;
let results = "";
if (length > 0) {
const sepPos = keys[0].lastIndexOf("_");
const prefix = keys[0].substring(0, sepPos);
for (let x = 0; x < length; x++) {
results += items[`${prefix}_${x}`];
}
results = results
.replaceAll("[", "")
.replaceAll("]", ",")
.replaceAll(" ", "")
.replaceAll('"', "")
.replaceAll('"', "")
.split(",")
.filter((element) => element !== "");
resolve(results);
return;
}
resolve([]);
});
});
});
}
function migrateStorage() {
// Step 1: Retrieve all items from storage.sync
browser.storage.sync.get(null, function (items) {
if (browser.runtime.lastError) {
console.error(`${logPrefix} Error retrieving sync storage:`, browser.runtime.lastError);
return;
}
// Step 2: Save the retrieved items to storage.local
browser.storage.local.set(items, function () {
if (browser.runtime.lastError) {
console.error(`${logPrefix} Error setting local storage:`, browser.runtime.lastError);
return;
}
console.log(`${logPrefix} Data migrated to local storage successfully.`);
});
});
}
// ==================== AUTO-PAGINATION FUNCTIONALITY ====================
function createSpinner() {
const spinner = document.createElement("div");
spinner.className = "avito-auto-pagination-loader-spinner";
spinner.style.display = "none";
spinner.style.position = "absolute";
spinner.style.right = "10px";
spinner.style.top = "50%";
spinner.style.transform = "translateY(-50%)";
spinner.style.border = "3px solid rgba(255, 255, 255, 0.3)";
spinner.style.borderTop = "3px solid white";
spinner.style.borderRadius = "50%";
spinner.style.width = "16px";
spinner.style.height = "16px";
spinner.style.animation = "spin 0.8s linear infinite";
// Add keyframes for spinner if not already added
if (!document.getElementById("avito-spinner-style")) {
const style = document.createElement("style");
style.id = "avito-spinner-style";
style.textContent = `
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
}
return spinner;
}
function getMainOffersContainer() {
const containers = document.querySelectorAll('[class*="items-items-"]');
return containers.length > 0 ? containers[0] : null;
}
function getOtherCitiesContainer() {
const containers = document.querySelectorAll('[class*="items-items-"]');
return containers.length > 1 ? containers[1] : null;
}
function isPaginatorVisible() {
const paginator = document.querySelector('[class*="js-pages pagination-pagination-"]');
if (!paginator) {
console.log(`${logPrefix} Paginator not found`);
return false;
}
const rect = paginator.getBoundingClientRect();
const isVisible = rect.top <= (window.innerHeight || document.documentElement.clientHeight) && rect.bottom >= 0;
// console.log(`${logPrefix} Paginator visibility check: ${isVisible}`);
return isVisible;
}
// Get current page number
function getCurrentPage() {
const currentPageElement = document.querySelector('[class*="styles-module-item_current-"]');
if (currentPageElement) {
const pageText = currentPageElement.querySelector("span")?.textContent;
const page = parseInt(pageText, 10) || 1;
console.log(`${logPrefix} Current page: ${page}`);
return page;
}
console.log(`${logPrefix} Current page not found, defaulting to 1`);
return 1;
}
function getNextPageUrl() {
const currentPage = getCurrentPage();
const nextPageElement = document.querySelector(`[data-value="${currentPage + 1}"]`);
const url = nextPageElement ? nextPageElement.href : null;
console.log(`${logPrefix} Next page URL: ${url}`);
return url;
}
function removeBrokenElements(item) {
item.querySelectorAll('[class*="photo-slider-extra"]').forEach((container) => {
container.remove();
});
item.querySelectorAll('[class*="iva-item-actions-"]').forEach((container) => {
container.remove();
});
}
// Fix missing images in an item
function fixItemImages(item) {
const imageContainers = item.querySelectorAll('[class*="photo-slider-dotsCounter"]');
imageContainers.forEach((container) => {
const imageMarker = container.getAttribute("data-marker");
if (!imageMarker || !imageMarker.startsWith("slider-image/image-")) return;
const imageUrl = imageMarker.replace("slider-image/image-", "");
const imageSpan = container.querySelector("[class*='photo-slider-image-']");
// If we have a span instead of an img, fix it
if (imageSpan && imageSpan.tagName === "SPAN") {
const img = document.createElement("img");
img.className = "photo-slider-image";
img.alt = item.querySelector('[itemprop="name"]')?.textContent || "";
img.src = imageUrl;
// Replace span with img
imageSpan.replaceWith(img);
}
});
}
// Process new items - fix images and add to DOM
function processNewItems(newItems, targetContainer) {
console.log(`${logPrefix} Processing ${newItems.length} new items into ${targetContainer.className}`);
newItems.forEach((offer) => {
const clone = offer.cloneNode(true);
removeBrokenElements(clone);
fixItemImages(clone);
targetContainer.appendChild(clone);
// Process the new offer
const offerId = getOfferId(clone);
const currentOfferData = catalogData.find((item) => item.id === Number(offerId));
let userId = null;
try {
// Если у нас есть userId напрямую из данных каталога
if (currentOfferData?.userId) {
userId = currentOfferData.userId;
} else {
// Пробуем извлечь из структуры iva
const sellerUrl = currentOfferData?.iva?.UserInfoStep[0]?.payload?.profile?.link;
if (sellerUrl) {
const userMatch = sellerUrl.match(/\/user\/([^\/]+)/);
const brandMatch = sellerUrl.match(/\/brands\/([^\/]+)/);
if (userMatch) {
userId = userMatch[1].split('?')[0]; // Убираем параметры после ?
} else if (brandMatch) {
userId = brandMatch[1].split('?')[0]; // Убираем параметры после ?
}
}
}
// Если не получилось из данных каталога, пробуем извлечь из DOM
if (!userId) {
const sellerLinkElement = clone.querySelector('a[href*="/user/"]') ||
clone.querySelector('a[href*="/brands/"]');
if (sellerLinkElement) {
const sellerHref = sellerLinkElement.href;
const userMatch = sellerHref.match(/\/user\/([^\/]+)/);
const brandMatch = sellerHref.match(/\/brands\/([^\/]+)/);
if (userMatch) {
userId = userMatch[1].split('?')[0]; // Убираем параметры после ?
} else if (brandMatch) {
userId = brandMatch[1].split('?')[0]; // Убираем параметры после ?
}
}
}
} catch (error) {
console.error("Error extracting userId:", error);
userId = undefined;
} finally {
updateOfferState(clone, { offerId, userId });
}
});
}
async function fetchNextPage() {
if (!isPaginationEnabled || isLoading) {
console.log(`${logPrefix} Fetch aborted - script disabled or already loading`);
return;
}
const spinner = createSpinner();
const nextPageUrl = getNextPageUrl();
if (!nextPageUrl) {
console.log(`${logPrefix} Все станицы получены`);
return;
}
isLoading = true;
console.log(`${logPrefix} Загрузка страницы ${getCurrentPage() + 1}`);
// Append spinner to pagination
const paginator = document.querySelector('[class*="js-pages pagination-pagination-"]');
if (paginator) {
paginator.style.position = "relative";
// Create status text element
const statusText = document.createElement("span");
statusText.className = "avito-pagination-status";
statusText.textContent = `Загрузка страницы ${getCurrentPage() + 1}`;
statusText.style.marginRight = "10px";
statusText.style.color = "#999";
statusText.style.fontSize = "14px";
// Add elements to pagination
spinner.style.display = "block";
paginator.appendChild(statusText);
paginator.appendChild(spinner);
}
try {
const response = await fetch(nextPageUrl);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
// Find all containers in the new page
const newContainers = doc.querySelectorAll('[class*="items-items"]');
console.log(`${logPrefix} Found ${newContainers.length} containers in new page`);
if (newContainers.length === 0) {
console.log(`${logPrefix} No containers found in new page`);
return;
}
// Find catalog data in the new page
const scriptElements = doc.querySelectorAll("script");
for (const script of scriptElements) {
if (script.textContent.includes("abCentral") && !script.textContent.startsWith("window[")) {
try {
const initCatalogDataContent = script.textContent;
const decodedJson = decodeHtmlEntities(initCatalogDataContent);
const newInitialData = JSON.parse(decodedJson);
const newCatalogData = getCatalogDataFromInit(newInitialData);
// Merge new catalog data with existing
catalogData = [...catalogData, ...newCatalogData];
console.log(`${logPrefix} Added ${newCatalogData.length} items to catalogData`);
break;
} catch (error) {
console.error(`${logPrefix} Error parsing catalog data from new page:`, error);
}
}
}
// Process main offers (first container)
const newMainOffers = Array.from(newContainers[0].children).filter((el) => el.hasAttribute("data-item-id"));
if (newMainOffers.length > 0) {
const mainContainer = getMainOffersContainer();
if (mainContainer) {
console.log(`${logPrefix} Adding ${newMainOffers.length} main offers`);
processNewItems(newMainOffers, mainContainer);
} else {
console.log(`${logPrefix} Main container not found`);
}
}
// Process other cities offers (second container if exists)
if (newContainers.length > 1) {
const newOtherCitiesOffers = Array.from(newContainers[1].children).filter((el) => el.hasAttribute("data-item-id"));
if (newOtherCitiesOffers.length > 0) {
let targetContainer = getOtherCitiesContainer();
if (!targetContainer) {
console.log(`${logPrefix} No existing other cities container - creating one`);
// Create new container if none exists
const mainContainer = getMainOffersContainer();
if (mainContainer) {
const newContainer = document.createElement("div");
newContainer.className = "items-items-";
mainContainer.after(newContainer);
targetContainer = newContainer;
}
}
if (targetContainer) {
console.log(`${logPrefix} Adding ${newOtherCitiesOffers.length} other cities offers`);
processNewItems(newOtherCitiesOffers, targetContainer);
}
}
}
// Update pagination
const newPaginator = doc.querySelector('[class*="js-pages pagination-pagination-"]');
if (newPaginator) {
if (paginator) {
paginator.innerHTML = newPaginator.innerHTML;
console.log(`${logPrefix} Updated pagination controls`);
}
}
console.log(`${logPrefix} Страница успешно загружена`);
} catch (error) {
console.error(`${logPrefix} Ошибка загрузки страницы:`, error);
} finally {
isLoading = false;
// Remove spinner and status text from pagination
spinner.style.display = "none";
if (spinner.parentNode) {
const statusText = spinner.parentNode.querySelector(".avito-pagination-status");
if (statusText) statusText.remove();
spinner.parentNode.removeChild(spinner);
}
}
}
function checkPaginationVisibility() {
if (!isPaginationEnabled || isLoading) return;
clearTimeout(checkTimeout);
checkTimeout = setTimeout(() => {
if (isPaginatorVisible()) {
fetchNextPage();
}
}, 200);
}
// Initialize MutationObserver to watch for paginator changes
function initPaginationObserver() {
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length) {
// console.log(`${logPrefix} DOM mutation detected, checking paginator visibility`);
checkPaginationVisibility();
}
});
});
// Observe the document body for added nodes
observer.observe(document, {
childList: true,
subtree: true,
});
return observer;
}
// Initialize pagination functionality
async function initPagination() {
console.log(`${logPrefix} Initializing Avito Auto-Pagination script`);
// Set up scroll listener
window.addEventListener("scroll", checkPaginationVisibility);
// Set up mutation observer
initPaginationObserver();
}
// ==================== CITY FILTER FUNCTIONALITY ====================
// Служебные пути Avito, которые не являются городами
const EXCLUDED_URL_PATHS = ['user', 'brands', 'companies', 'shops', 'profile', 'favorites', 'messages'];
// CSS класс Avito для визуального состояния "включено" у переключателя
// Примечание: класс содержит хеш, который может измениться при обновлении Avito
const TOGGLE_CHECKED_CLASS = 'styles-module-controlledInput_checked-fJhQQ';
// Извлечение города из URL (общая функция)
function extractCityFromUrl(url) {
if (!url) return null;
const match = url.match(/avito\.ru\/([a-z_]+)/i);
if (match && match[1]) {
const path = match[1].toLowerCase();
if (!EXCLUDED_URL_PATHS.includes(path)) {
return path;
}
}
return null;
}
// Извлечение города из URL страницы
function getCityFromPageUrl() {
return extractCityFromUrl(window.location.href);
}
// Извлечение города из URL объявления
function getCityFromOfferUrl(url) {
return extractCityFromUrl(url);
}
// Получение URL объявления из DOM элемента
function getOfferUrl(offerElement) {
// Ищем ссылку на объявление в элементе
const titleLink = offerElement.querySelector('[data-marker="item-title"]');
if (titleLink && titleLink.href) {
return titleLink.href;
}
// Альтернативный поиск ссылки
const anyLink = offerElement.querySelector('a[href*="/"]');
if (anyLink && anyLink.href && anyLink.href.includes('avito.ru/')) {
return anyLink.href;
}
return null;
}
// Получение читаемого названия города из UI (из элемента "Сначала из Тюмени")
function getCityDisplayName() {
const localPriorityLabel = document.querySelector('.filters-switcherLabel-vbkFI');
if (localPriorityLabel) {
const text = localPriorityLabel.textContent;
// Извлекаем название города из "Сначала из Тюмени" -> "Тюмени"
const match = text.match(/Сначала из (.+)/);
if (match && match[1]) {
return match[1];
}
}
// Fallback: используем город из URL
const cityLat = getCityFromPageUrl();
return cityLat || 'города';
}
// Проверка, принадлежит ли объявление текущему городу
function isOfferFromCurrentCity(offerElement) {
const currentCity = getCityFromPageUrl();
if (!currentCity) return true; // Если не можем определить город, не фильтруем
const offerUrl = getOfferUrl(offerElement);
if (!offerUrl) return true; // Если нет URL, не фильтруем
const offerCity = getCityFromOfferUrl(offerUrl);
if (!offerCity) return true; // Если не можем определить город объявления, не фильтруем
return offerCity === currentCity;
}
// Установка визуального состояния переключателя (checkbox + label)
function setToggleVisualState(checkbox, label, isEnabled) {
if (checkbox) {
checkbox.checked = isEnabled;
checkbox.classList.toggle(TOGGLE_CHECKED_CLASS, isEnabled);
}
if (label) {
label.setAttribute('aria-checked', isEnabled ? 'true' : 'false');
}
}
// Обновление визуального состояния переключателя города
function updateCityFilterToggleState() {
const label = document.querySelector('[data-marker="filters/cityOnly"]');
if (!label) return;
const checkbox = label.querySelector('input[type="checkbox"]');
setToggleVisualState(checkbox, label, cityFilterEnabled);
}
// Создание UI переключателя "Только из [город]"
function insertCityFilterToggle() {
// Проверяем, не добавлен ли уже переключатель
const existingToggle = document.querySelector('[data-marker="filters/cityOnly"]');
if (existingToggle) {
// Обновляем состояние существующего переключателя
updateCityFilterToggleState();
return;
}
// Ищем панель с переключателем "Сначала из..."
const topPanel = document.querySelector('[class*="index-topPanel-"]');
if (!topPanel) {
console.log(`${logPrefix} Верхняя панель не найдена для вставки переключателя города`);
return;
}
// Ищем существующий переключатель "Сначала из..." для копирования структуры
const existingToggleContainer = topPanel.querySelector('[data-marker="filters/localPriority/localPriority"]');
if (!existingToggleContainer) {
console.log(`${logPrefix} Существующий переключатель не найден`);
return;
}
const cityName = getCityDisplayName();
// Клонируем родительский контейнер переключателя
const parentContainer = existingToggleContainer.closest('.styles-module-theme-CW0hC');
if (!parentContainer) {
console.log(`${logPrefix} Родительский контейнер не найден`);
return;
}
const newContainer = parentContainer.cloneNode(true);
// Настраиваем label
const newLabel = newContainer.querySelector('label');
if (newLabel) {
newLabel.setAttribute('data-marker', 'filters/cityOnly');
}
// Изменяем текст
const labelText = newContainer.querySelector('.filters-switcherLabel-vbkFI');
if (labelText) {
labelText.textContent = `Только из ${cityName}`;
}
// Настраиваем checkbox
const checkbox = newContainer.querySelector('input[type="checkbox"]');
if (checkbox) {
checkbox.name = 'cityOnly';
checkbox.value = 'cityOnly';
checkbox.setAttribute('data-marker', 'filters/cityOnly/toggle');
// Устанавливаем начальное визуальное состояние
setToggleVisualState(checkbox, newLabel, cityFilterEnabled);
// Обработчик изменения checkbox
checkbox.addEventListener('change', function() {
cityFilterEnabled = this.checked;
setToggleVisualState(this, newLabel, cityFilterEnabled);
browser.storage.local.set({ isCityFilterEnabled: cityFilterEnabled });
console.log(`${logPrefix} Фильтр по городу: ${cityFilterEnabled ? 'включен' : 'выключен'}`);
processSearchPage();
});
}
// Вставляем новый переключатель после существующего
parentContainer.after(newContainer);
console.log(`${logPrefix} Переключатель "Только из ${cityName}" добавлен`);
}
// ==================== MAIN FUNCTIONALITY ====================
function getSellerId(initialData) {
const customLink = initialData.data.ssrData.initData.result.value.data.customLink;
const profileUserHash = initialData.data.ssrData.initData.result.value.data.profileUserHash;
// Поддерживаем как /user/ так и /brands/ ссылки
if (customLink) {
const userMatch = customLink.match(/\/user\/([^\/]+)/);
const brandMatch = customLink.match(/\/brands\/([^\/]+)/);
if (userMatch) {
return userMatch[1].split('?')[0]; // Убираем параметры после ?
} else if (brandMatch) {
// Для брендов используем ID бренда
return brandMatch[1].split('?')[0]; // Убираем параметры после ?
}
}
return profileUserHash;
}
function getCatalogData(initCatalogData) {
// Проверяем существование необходимых свойств
if (!initCatalogData || !initCatalogData.data || !initCatalogData.data.catalog) {
console.warn(`${logPrefix} Неверная структура initCatalogData:`, initCatalogData);
return [];
}
const catalogItems = initCatalogData.data.catalog.items || [];
const extraItems = initCatalogData.data.catalog.extraBlockItems || [];
let allItems = catalogItems.concat(extraItems);
allItems = allItems.filter((item) => item.hasOwnProperty("categoryId"));
return allItems;
}
function parseInitialData(initialDataContent) {
try {
initialDataContent = decodeURIComponent(initialDataContent);
// Find the start and end indexes of __initialData__ JSON
const startIndex = initialDataContent.indexOf('window.__initialData__ = "') + 'window.__initialData__ = "'.length;
const endIndex = initialDataContent.indexOf('";\nwindow.__mfe__');
// Extract the JSON string
const jsonString = initialDataContent.substring(startIndex, endIndex);
// Parse the JSON string into a JavaScript object
const initialData = JSON.parse(jsonString);
return initialData;
} catch (error) {
console.error(`${logPrefix} Ошибка парсинга __initialData__:`, error);
}
return null;
}
function addUserToBlacklist(userId) {
let searchId = userId + "_blacklist_user";
let inBlacklist = blacklistUsers.includes(searchId);
if (!inBlacklist) {
blacklistUsers.push(searchId);
syncStore("blacklistUsers", blacklistUsers);
}
console.log(`${logPrefix} продавец ${userId} добавлен в блеклист`);
}
function addOfferToBlacklist(offerId) {
let searchId = offerId + "_blacklist_ad";
let inBlacklist = blacklistOffers.includes(searchId);
if (!inBlacklist) {
blacklistOffers.push(searchId);
syncStore("blacklistOffers", blacklistOffers);
}
console.log(`${logPrefix} объявление ${offerId} добавлено в блеклист`);
}
function removeUserFromBlacklist(userId) {
let searchId = userId + "_blacklist_user";
let inBlacklist = blacklistUsers.includes(searchId);
if (inBlacklist) {
blacklistUsers = blacklistUsers.filter((userId) => userId !== searchId);
syncStore("blacklistUsers", blacklistUsers);
}
console.log(`${logPrefix} продавец ${userId} удален из блеклиста`);
}
function removeOfferFromBlacklist(offerId) {
let searchId = offerId + "_blacklist_ad";
let inBlacklist = blacklistOffers.includes(searchId);
if (inBlacklist) {
blacklistOffers = blacklistOffers.filter((offerId) => offerId !== searchId);
syncStore("blacklistOffers", blacklistOffers);
}
console.log(`${logPrefix} объявление ${offerId} удалено из блеклиста`);
}
function getOfferId(offerElement) {
return offerElement.getAttribute("data-item-id");
}
function createHiddenContainer() {
const offersRoot = document.querySelector(offersRootSelector);
const hr = document.createElement("hr");
hr.classList.add("custom-hr");
const existingContainerEl = document.querySelector(".hidden-container");
if (existingContainerEl) return existingContainerEl;
// Create the <details> element
const detailsElement = document.createElement("details");
// Create the <summary> element
const summaryElement = document.createElement("summary");
summaryElement.textContent = "Скрытые объявления";
summaryElement.classList.add("custom-summary");
// Create content for the <details> element
const contentElement = document.createElement("div");
contentElement.classList.add("hidden-container");
// Append the <summary> and content to the <details> element
detailsElement.appendChild(summaryElement);
detailsElement.appendChild(contentElement);
// Append the <details> element to the document body or another element
offersRoot.appendChild(hr);
offersRoot.appendChild(detailsElement);
return contentElement;
}
function insertBlockSellerButton(offerElement, offerInfo) {
let buttonContainer = offerElement.querySelector(".button-container");
if (!buttonContainer) {
buttonContainer = insertButtonContainer(offerElement);
}
const blockButton = document.createElement("div");
blockButton.title = "Скрыть все объявления продавца";