Skip to content

Commit baffd32

Browse files
committed
Improve trusted-create-html scriptlet
1 parent 2ce376c commit baffd32

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/js/resources/create-html.js

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,26 +71,34 @@ function trustedCreateHTML(
7171
const duration = parseInt(durationStr, 10);
7272
const domParser = new DOMParser();
7373
const externalDoc = domParser.parseFromString(htmlStr, 'text/html');
74-
const docFragment = new DocumentFragment();
75-
const toRemove = [];
74+
const toAppend = [];
7675
while ( externalDoc.body.firstChild !== null ) {
77-
const imported = document.adoptNode(externalDoc.body.firstChild);
78-
docFragment.appendChild(imported);
79-
if ( isNaN(duration) ) { continue; }
80-
toRemove.push(imported);
76+
toAppend.push(document.adoptNode(externalDoc.body.firstChild));
8177
}
82-
if ( docFragment.firstChild === null ) { return; }
78+
if ( toAppend.length === 0 ) { return; }
79+
const toRemove = [];
8380
const remove = ( ) => {
8481
for ( const node of toRemove ) {
8582
if ( node.parentNode === null ) { continue; }
8683
node.parentNode.removeChild(node);
8784
}
8885
safe.uboLog(logPrefix, 'Node(s) removed');
8986
};
87+
const appendOne = (target, nodes) => {
88+
for ( const node of nodes ) {
89+
target.append(node);
90+
if ( isNaN(duration) ) { continue; }
91+
toRemove.push(node);
92+
}
93+
};
9094
const append = ( ) => {
91-
const parent = document.querySelector(parentSelector);
92-
if ( parent === null ) { return false; }
93-
parent.append(docFragment);
95+
const targets = document.querySelectorAll(parentSelector);
96+
if ( targets.length === 0 ) { return false; }
97+
const limit = Math.min(targets.length, extraArgs.limit || 1) - 1;
98+
for ( let i = 0; i < limit; i++ ) {
99+
appendOne(targets[i], toAppend.map(a => a.cloneNode(true)));
100+
}
101+
appendOne(targets[limit], toAppend);
94102
safe.uboLog(logPrefix, 'Node(s) appended');
95103
if ( toRemove.length === 0 ) { return true; }
96104
setTimeout(remove, duration);

0 commit comments

Comments
 (0)