-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
384 lines (345 loc) · 14 KB
/
popup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// adds save button event to popup page
$(function() {
$('#saveImages').click(function(){saveButtonClick(true)});
$('#save').click(function(){saveButtonClick()});
});
var selectors = ['title', 'price', 'description', 'locality', 'street', 'shipping', 'condition', 'images'];
function saveButtonClick(withImages = false) {
var newItem = {};
Promise.all(selectors.map(currSelector => DOMgetValue(currSelector))).then(function(results) {
newItem.title = results[0];
newItem.price = results[1].split(' ')[0];
if (results[1].includes('VB')) {
newItem.priceType = 1;
} else if (newItem.price.includes('verschenken')) {
newItem.priceType = 2;
} else {
newItem.priceType = 0;
}
newItem.description = results[2];
newItem.postCode = results[3].trim().split(' ')[0];
newItem.street = results[4];
if (newItem.street.includes('querySelector')) {
newItem.street = "";
}
newItem.shipping = results[5].trim().split(' ')[3];
newItem.condition = results[6].trim();
newItem.date = new Date().toLocaleDateString('de-de');
if (withImages) {
results[7].forEach(image => {
chrome.downloads.download({url: image}); // needs permission "downloads"!
});
newItem.images = results[7].map(function(image) {
return image.split('/').pop().split('?')[0] + '.jpg';
});
} else {
newItem.images = [];
}
// document.getElementById('test').innerText = JSON.stringify(newItem);
// return;
var items = {};
chrome.storage.sync.get('allItems', function(data) { // needs permission "storage"!
if (data) {
items = data.allItems;
}
items.push(newItem)
chrome.storage.sync.set({'allItems' : items});
});
}).catch(function(error) {
console.error('Error:', error);
});
}
// selects and returns dom elements content by query selector
function DOMgetValue(selector) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) { // needs permission "activeTab"!
var activeTab = tabs[0];
var activeTabId = activeTab.id;
document.querySelector('#errorMsg').innerText = "";
var keyWordID = selectors.indexOf(selector);
if (activeTab.url.includes('https://www.kleinanzeigen.de/s-anzeige')) {
selector = ['#viewad-title', '#viewad-price', '#viewad-description-text', '#viewad-locality', '#street-address', '.boxedarticle--details--shipping', '#addetailslist--detail--value', '#viewad-image>data-imgsrc'][keyWordID];
} else if (activeTab.url.includes('https://www.kleinanzeigen.de/p-anzeige')) {
selector = ['#postad-title>value', '#micro-frontend-price>value', '#pstad-descrptn>value', '#pstad-zip>value', '#pstad-street>value', '#jsx-3271908351 PackageSizeItem--Price>value', '.jsx-3300347113>value', '.imagebox-new-thumbnail--cover>data-xxl'][keyWordID];
} else {
document.querySelector('#errorMsg').innerText = "page not supported!";
throw new Error('Page Type not implemented!');
}
if (selector.includes('>value')) {
selector = selector.split('>')[0];
var retVal = chrome.scripting.executeScript({ // needs permission "scripting"!
target: { tabId: activeTabId },
func: DOMvalueToString,
args: [selector]
});
if (retVal == null) {
var attribute = selector.split('>')[1];
retVal = chrome.scripting.executeScript({ // needs permission "scripting"!
target: { tabId: activeTabId },
func: DOMattributeToArray,
args: [selector, attribute]
});
}
return retVal;
} else if (selector.includes('>')) {
var attribute = selector.split('>')[1];
selector = selector.split('>')[0];
return chrome.scripting.executeScript({ // needs permission "scripting"!
target: { tabId: activeTabId },
func: DOMattributeToArray,
args: [selector, attribute]
});
} else {
console.log(selector);
return chrome.scripting.executeScript({ // needs permission "scripting"!
target: { tabId: activeTabId },
func: DOMtoString,
args: [selector]
});
}
}).then(function (results) {
return results[0].result;
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// reats dom elements innerText by selector and returns as string
function DOMtoString(selector) {
if (selector) {
selector = document.querySelector(selector);
if (!selector) return "ERROR: querySelector failed to find node"
} else {
selector = document.documentElement;
}
return selector.innerText;
}
// reats dom elements value by selector and returns as string
function DOMvalueToString(selector) {
if (selector) {
selector = document.querySelector(selector);
if (!selector) return "ERROR: querySelector failed to find node"
} else {
selector = document.documentElement;
}
return selector.value;
}
// reats dom elements value attribute by selector and returns as array
function DOMattributeToArray(selector, attribute) {
let elements;
if (selector) {
elements = document.querySelectorAll(selector);
if (!elements.length) return "ERROR: querySelector failed to find nodes";
} else {
elements = [document.documentElement];
}
let values = [];
elements.forEach(element => {
let value = attribute ? element.getAttribute(attribute) : element.innerHTML;
values.push(value);
});
return values;
}
// sets value of e.g. input in dom by query selector
function DOMSetValue(selector, value) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
var activeTab = tabs[0];
var activeTabId = activeTab.id;
return chrome.scripting.executeScript({
target: { tabId: activeTabId },
func: (selector, value) => {
const element = document.querySelector(selector);
if (element) {
element.value = value;
}
},
args: [selector, value]
});
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// sets index of list in dom by query selector
function DOMSetIndex(selector, value) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
var activeTab = tabs[0];
var activeTabId = activeTab.id;
return chrome.scripting.executeScript({
target: { tabId: activeTabId },
func: (selector, value) => {
const element = document.querySelector(selector);
if (element) {
element.selectedIndex = value;
}
},
args: [selector, value]
});
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// sets checkbox state in dom by query selector
function DOMSetCheckbox(selector, value) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
var activeTab = tabs[0];
var activeTabId = activeTab.id;
return chrome.scripting.executeScript({
target: { tabId: activeTabId },
func: (selector, value) => {
const element = document.querySelector(selector);
if (element) {
element.checked = value;
}
},
args: [selector, value]
});
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// changes atribute of element in dom by query selector
function DOMChangeAttribute(selector, oldValue, newValue) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
var activeTab = tabs[0];
var activeTabId = activeTab.id;
return chrome.scripting.executeScript({
target: { tabId: activeTabId },
func: (selector, value) => {
const element = document.querySelector(selector);
if (element) {
element.removeAttribute(oldValue, "");
element.setAttribute(newValue, "");
}
},
args: [selector, value]
});
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// stets innerText of dom by query selector
function DOMSetTextContent(selector, value) {
return chrome.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
var activeTab = tabs[0];
var activeTabId = activeTab.id;
return chrome.scripting.executeScript({
target: { tabId: activeTabId },
func: (selector, value) => {
const element = document.querySelector(selector);
if (element) {
element.textContent = value;
}
},
args: [selector, value]
});
}).catch(function (error) {
throw new Error('There was an error injecting script: ' + error.message);
});
}
// displays list of all currently stored items
function showItems() {
allItems = chrome.storage.sync.get('allItems', function(data) {
if (data) {
const container = document.getElementById('item-list');
container.textContent = '';
// if no data exists
if (data.allItems == null) {
const itemDiv = document.createElement('div');
itemDiv.innerHTML = `<div class="no-items">no items</div>`
container.appendChild(itemDiv);
return;
}
// if the List exists but its empty
if (data.allItems.length < 1) {
const itemDiv = document.createElement('div');
itemDiv.innerHTML = `<div class="no-items">no items</div>`
container.appendChild(itemDiv);
return;
}
// if there is data in the list
data.allItems.forEach((item, index) => {
const itemDiv = document.createElement('div');
itemDiv.className = 'item';
itemDiv.id = 'item_' + (index + 1);
itemDiv.innerHTML = `
<div class="item-info">
<div class="item-details">
<div class="item-title">${item.title}</div>
<div class="item-price">${item.price} €</div>
<div class="item-date">Gespeichert am ${item.date}</div>
</div>
</div>
<div class="item-buttons">
<button id="load_${index + 1}">Load</button>
<button id="delete_${index + 1}">Delete</button>
</div>`;
container.appendChild(itemDiv);
});
container.addEventListener('click', handleButtonClick);
}
});
}
// manages button click events of item buttons
function handleButtonClick(event) {
const target = event.target;
if (target.tagName === 'BUTTON') {
const buttonId = target.id;
const itemId = buttonId.split('_')[1];
if (itemId >= 0) {
if (buttonId.startsWith('load')) {
handleLoadClick(itemId);
} else if (buttonId.startsWith('delete')) {
handleDeleteClick(itemId);
}
}
}
}
// fills form from stored items
function handleLoadClick(id) {
chrome.storage.sync.get('allItems', function(data) {
if (data) {
if (id <= data.allItems.length) {
let item = data.allItems[id - 1];
DOMSetValue('#postad-title', item.title);
DOMSetValue('#micro-frontend-price', item.price.split(' ')[0]);
DOMSetIndex('#micro-frontend-price-type', (item.priceType + 1));
DOMSetValue('#pstad-descrptn', item.description);
DOMSetTextContent('#jsx-3300347113', item.condition);
DOMSetValue('#pstad-zip', item.postCode)
if (item.street.length > 1){
DOMSetCheckbox('#addressVisibility', true);
DOMChangeAttribute('#pstad-street', 'disabled', 'enabled')
DOMSetValue('#pstad-street', item.street);
} else {
DOMSetCheckbox('#addressVisibility', false);
DOMChangeAttribute('#pstad-street', 'enabled', 'disabled')
DOMSetValue('#pstad-street', "");
}
}
}
});
}
// remove item from the list in storage and refresh popup page
function handleDeleteClick(id) {
chrome.storage.sync.get('allItems', function(data) {
if (data) {
if (id <= data.allItems.length) {
let items = [];
data.allItems.forEach((item, index) => {
if ((index + 1) != id) {
items.push(item);
}
});
chrome.storage.sync.set({'allItems' : items});
}
}
});
}
// add listener to fire reload event if item list in storage has changed
chrome.storage.onChanged.addListener(function() {
chrome.storage.sync.get({
profileId: 0
}, function() {
showItems();
});
});
// initial loading of already stored items
window.onload = showItems;