This repository has been archived by the owner on Dec 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
hideRemoveElements.ts
73 lines (64 loc) · 2.5 KB
/
hideRemoveElements.ts
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
import { WebElement } from 'selenium-webdriver';
/**
* Hide or remove elements on the page
*/
export default function hideRemoveElements(
hideRemoveElements: {
hide: (HTMLElement | HTMLElement[] | WebElement | WebElement[])[];
remove: (HTMLElement | HTMLElement[])[];
},
hideRemove: boolean,
): any {
const visitedSelectors: Record<string, boolean> = {};
hideRemoveElements.hide.forEach((element) => {
if (Array.isArray(element)) {
return element.forEach((singleElement: HTMLElement | WebElement) => hideRemoveEl(singleElement, 'visibility', hideRemove));
}
hideRemoveEl(element, 'visibility', hideRemove);
});
hideRemoveElements.remove.forEach((element) => {
if (Array.isArray(element)) {
return element.forEach((singleElement: HTMLElement | WebElement) => hideRemoveEl(singleElement, 'display', hideRemove));
}
hideRemoveEl(element, 'display', hideRemove);
});
function hideRemoveEl(el: HTMLElement | WebElement, prop: string, hideRemove: boolean) {
// @ts-ignore
if (el.style) {
// Here we get the HTMLElement
// @ts-ignore
setPropertyToElement(el, prop, hideRemove);
} else {
// Here we have the WebElement, with the web element we can have 2 types of selectors
// css and xpath, transform them into HTML
// This is an anti pattern, but I don't know how to do this better with XPATH selection
try {
// @ts-ignore
const selector = el.selector;
if (visitedSelectors[selector] == null) {
visitedSelectors[selector] = true;
const elems = document.querySelectorAll(selector);
elems.forEach((singleEl) => setPropertyToElement(singleEl, prop, hideRemove));
}
} catch (e) {
// 99.99% sure that we have XPATH here
// @ts-ignore
return getElementsByXpath(el.selector).forEach((singleEl) => setPropertyToElement(singleEl, prop, hideRemove));
}
}
}
function setPropertyToElement(el: HTMLElement, prop: string, hideRemove: boolean) {
const value = prop === 'visibility' ? 'hidden' : 'none';
// @ts-ignore
el.style[prop] = hideRemove ? value : '';
}
// Stupid TypeScript =)
function getElementsByXpath(xpathToExecute: string): any[] {
const result = [];
const nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < nodesSnapshot.snapshotLength; i++) {
result.push(nodesSnapshot.snapshotItem(i));
}
return result;
}
}