-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtrusted-create-element.ts
209 lines (191 loc) · 6.58 KB
/
trusted-create-element.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
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
import {
hit,
logMessage,
observeDocumentWithTimeout,
nativeIsNaN,
parseAttributePairs,
getErrorMessage,
} from '../helpers';
import type { ParsedAttributePair } from '../helpers';
import { type Source } from './scriptlets';
/* eslint-disable max-len */
/**
* @trustedScriptlet trusted-create-element
*
* @description
* Creates an element with specified attributes and text content, and appends it to the specified parent element.
*
* ### Syntax
*
* <!-- markdownlint-disable line-length -->
*
* ```text
* example.com#%#//scriptlet('trusted-create-element', parentSelector, tagName[, attributePairs[, textContent[, cleanupDelayMs]]])
* ```
*
* <!-- markdownlint-enable line-length -->
*
* - `parentSelector` — required, CSS selector of the parent element to append the created element to.
* - `tagName` — required, tag name of the created element.
* - `attributePairs` — optional, space-separated list of attribute name and value pairs separated by `=`.
* Value can be omitted. If value is set, it should be wrapped in quotes.
* If quotes are needed inside value, they should be escaped with backslash.
* Defaults to no attributes.
* - `textContent` — optional, text content of the created element. Defaults to empty string.
* - `cleanupDelayMs` — optional, delay in milliseconds before the created element is removed from the DOM.
* Defaults to no cleanup.
*
* ### Examples
*
* 1. Create a div element with a single attribute
*
* ```adblock
* example.com#%#//scriptlet('trusted-create-element', 'body', 'div', 'data-cur="1"')
* ```
*
* 1. Create a div element with text content
*
* ```adblock
* example.com#%#//scriptlet('trusted-create-element', 'body', 'div', '', 'Hello world!')
* ```
*
* 1. Create a button element with multiple attributes, including attribute without value, and text content
*
* <!-- markdownlint-disable line-length -->
*
* ```adblock
* example.com#%#//scriptlet('trusted-create-element', 'body', 'button', 'disabled aria-hidden="true" style="width: 0px"', 'Press here')
* ```
*
* <!-- markdownlint-enable line-length -->
*
* 1. Create a button element with an attribute whose value contains quotes
*
* ```adblock
* example.com#%#//scriptlet('trusted-create-element', 'body', 'button', 'data="a\\"quote"')
* ```
*
* 1. Create a paragraph element with text content and remove it after 5 seconds
*
* ```adblock
* example.com#%#//scriptlet('trusted-create-element', '.container > article', 'p', '', 'Hello world!', '5000')
* ```
*
* @added v1.10.1.
*/
/* eslint-enable max-len */
export function trustedCreateElement(
source: Source,
parentSelector: string,
tagName: string,
attributePairs = '',
textContent = '',
cleanupDelayMs = NaN,
) {
if (!parentSelector || !tagName) {
return;
}
/**
* Prevent infinite loops when creating iframes
* because scriptlet is automatically injected into the newly created iframe.
*/
const IFRAME_WINDOW_NAME = 'trusted-create-element-window';
if (window.name === IFRAME_WINDOW_NAME) {
return;
}
const logError = (prefix: string, error: unknown) => {
logMessage(source, `${prefix} due to ${getErrorMessage(error)}`);
};
let element: HTMLElement;
try {
element = document.createElement(tagName);
element.textContent = textContent;
} catch (e) {
logError(`Cannot create element with tag name '${tagName}'`, e);
return;
}
let attributes: ParsedAttributePair[] = [];
try {
attributes = parseAttributePairs(attributePairs);
} catch (e) {
logError(`Cannot parse attributePairs param: '${attributePairs}'`, e);
return;
}
attributes.forEach((attr) => {
try {
element.setAttribute(attr.name, attr.value);
} catch (e) {
logError(`Cannot set attribute '${attr.name}' with value '${attr.value}'`, e);
}
});
let timerId: ReturnType<typeof setTimeout>;
let elementCreated = false;
let elementRemoved = false;
/**
* Finds parent element by `parentElSelector` and appends the `el` element to it.
*
* If `removeElDelayMs` is not `NaN`,
* schedules the `el` element to be removed after `removeElDelayMs` milliseconds.
*
* @param parentElSelector CSS selector of the parent element.
* @param el HTML element to append to the parent element.
* @param removeElDelayMs Delay in milliseconds after which the `el` element is removed from the DOM.
*
* @returns True if the `el` element was successfully appended to the parent element, otherwise false.
*/
const findParentAndAppendEl = (parentElSelector: string, el: HTMLElement, removeElDelayMs: number) => {
let parentEl;
try {
parentEl = document.querySelector(parentElSelector);
} catch (e) {
logError(`Cannot find parent element by selector '${parentElSelector}'`, e);
return false;
}
if (!parentEl) {
logMessage(source, `No parent element found by selector: '${parentElSelector}'`);
return false;
}
try {
if (!parentEl.contains(el)) {
parentEl.append(el);
}
if (el instanceof HTMLIFrameElement && el.contentWindow) {
el.contentWindow.name = IFRAME_WINDOW_NAME;
}
elementCreated = true;
hit(source);
} catch (e) {
logError(`Cannot append child to parent by selector '${parentElSelector}'`, e);
return false;
}
if (!nativeIsNaN(removeElDelayMs)) {
timerId = setTimeout(() => {
el.remove();
elementRemoved = true;
clearTimeout(timerId);
}, removeElDelayMs);
}
return true;
};
if (!findParentAndAppendEl(parentSelector, element, cleanupDelayMs)) {
observeDocumentWithTimeout((mutations, observer) => {
if (elementRemoved || elementCreated || findParentAndAppendEl(parentSelector, element, cleanupDelayMs)) {
observer.disconnect();
}
});
}
}
export const trustedCreateElementNames = [
'trusted-create-element',
// trusted scriptlets support no aliases
];
// eslint-disable-next-line prefer-destructuring
trustedCreateElement.primaryName = trustedCreateElementNames[0];
trustedCreateElement.injections = [
hit,
logMessage,
observeDocumentWithTimeout,
nativeIsNaN,
parseAttributePairs,
getErrorMessage,
];