Skip to content

Commit 9547fbf

Browse files
domeniccodex
andauthored
Tie queued tasks to document lifetime
Track document destruction explicitly instead of deleting window.document and clearing its DOM during window.close(). Preserve DOM access through retained references while preventing new script execution, subresource loading, timers, and animation frames in destroyed documents. Continue rejecting XHR open() and send() after document destruction. Associate queued events and navigation work with their documents, discarding tasks after destruction. Element tasks use their relevant global's associated document, including after adoption. Keep window.stop() limited to stopping requests rather than discarding unrelated tasks. Destroy descendant documents inside shadow trees as well as ordinary child frames. Mark destruction before aborting requests so abort listeners can safely reenter window.close(). Separate internal document loading completion from the public load event so a child that removes itself during loading does not leave its parent waiting forever. Preserve completion of already-running algorithms: external scripts still fire load after execution or cleanup microtasks remove their iframe, and FileReader still fires loadend after a load listener removes its iframe. Cover these specified completion rules with WPTs despite differences between browser engines. Store the associated DocumentImpl directly on windows and expose its wrapper through the public document getter. Document destruction remains distinct from window.closed and from a document not being fully active; task sources and suspension/resumption of inactive documents remain unimplemented. Co-authored-by: codex <[email protected]>
1 parent 3be65d9 commit 9547fbf

44 files changed

Lines changed: 688 additions & 186 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎benchmark/dom/document-tasks.js‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"use strict";
2+
const { Bench } = require("tinybench");
3+
const { JSDOM } = require("../..");
4+
5+
module.exports = () => {
6+
const bench = new Bench();
7+
const { window } = new JSDOM();
8+
const audio = window.document.createElement("audio");
9+
10+
bench.add("dispatch 100 queued media events", async () => {
11+
const completed = new Promise(resolve => {
12+
let remaining = 100;
13+
audio.onvolumechange = () => {
14+
if (--remaining === 0) {
15+
resolve();
16+
}
17+
};
18+
});
19+
for (let i = 0; i < 100; ++i) {
20+
audio.volume = i % 2;
21+
}
22+
await completed;
23+
});
24+
25+
bench.add("dispatch 100 queued messages", async () => {
26+
const completed = new Promise(resolve => {
27+
let remaining = 100;
28+
window.onmessage = () => {
29+
if (--remaining === 0) {
30+
resolve();
31+
}
32+
};
33+
});
34+
for (let i = 0; i < 100; ++i) {
35+
window.postMessage("message", "*");
36+
}
37+
await completed;
38+
});
39+
40+
return bench;
41+
};

‎lib/api.js‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class JSDOM {
4040

4141
this[window] = createWindow(options.windowOptions);
4242

43-
const documentImpl = idlUtils.implForWrapper(this[window]._document);
43+
const documentImpl = this[window]._document;
4444

4545
options.beforeParse(this[window]._globalProxy);
4646

@@ -61,15 +61,15 @@ class JSDOM {
6161

6262
get cookieJar() {
6363
// TODO NEWAPI move _cookieJar to window probably
64-
return idlUtils.implForWrapper(this[window]._document)._cookieJar;
64+
return this[window]._document._cookieJar;
6565
}
6666

6767
serialize() {
68-
return fragmentSerialization(idlUtils.implForWrapper(this[window]._document), { requireWellFormed: false });
68+
return fragmentSerialization(this[window]._document, { requireWellFormed: false });
6969
}
7070

7171
nodeLocation(node) {
72-
if (!idlUtils.implForWrapper(this[window]._document)._parseOptions.sourceCodeLocationInfo) {
72+
if (!this[window]._document._parseOptions.sourceCodeLocationInfo) {
7373
throw new Error("Location information was not saved for this jsdom. Use includeNodeLocations during creation.");
7474
}
7575

@@ -91,7 +91,7 @@ class JSDOM {
9191
}
9292

9393
if ("url" in settings) {
94-
const document = idlUtils.implForWrapper(this[window]._document);
94+
const document = this[window]._document;
9595

9696
const url = whatwgURL.parseURL(settings.url);
9797
if (url === null) {

‎lib/jsdom/browser/Window.js‎

Lines changed: 49 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -123,20 +123,20 @@ exports.createWindow = options => {
123123

124124
// Fire or prepare to fire load and pageshow events.
125125
process.nextTick(() => {
126-
if (!window.document) {
127-
return; // window might've been closed already
126+
const documentImpl = window._document;
127+
if (documentImpl._isDestroyed) {
128+
return;
128129
}
129130

130131
if (window.document.readyState === "complete") {
131132
fireAnEvent("load", window, undefined, {}, true);
132133
} else {
133134
window.document.addEventListener("load", () => {
134135
fireAnEvent("load", window, undefined, {}, true);
135-
if (!window._document) {
136-
return; // window might've been closed already
136+
if (documentImpl._isDestroyed) {
137+
return;
137138
}
138139

139-
const documentImpl = idlUtils.implForWrapper(window._document);
140140
if (!documentImpl._pageShowingFlag) {
141141
documentImpl._pageShowingFlag = true;
142142
fireAPageTransitionEvent("pageshow", window, false);
@@ -195,7 +195,7 @@ function installOwnProperties(window, options) {
195195
window._userAgent = options.userAgent;
196196

197197
// List options explicitly to be clear which are passed through
198-
window._document = documents.createWrapper(window, {
198+
window._document = documents.createImpl(window, {
199199
parsingMode: options.parsingMode,
200200
contentType: options.contentType,
201201
encoding: options.encoding,
@@ -210,13 +210,13 @@ function installOwnProperties(window, options) {
210210
parentOrigin: options.parentOrigin
211211
}, { alwaysUseDocumentClass: true });
212212

213-
const documentOrigin = idlUtils.implForWrapper(window._document)._origin;
213+
const documentOrigin = window._document._origin;
214214
window._origin = documentOrigin;
215215

216216
// https://html.spec.whatwg.org/#session-history
217217
window._sessionHistory = new SessionHistory({
218-
document: idlUtils.implForWrapper(window._document),
219-
url: idlUtils.implForWrapper(window._document)._URL,
218+
document: window._document,
219+
url: window._document._URL,
220220
stateObject: null
221221
}, window);
222222

@@ -373,20 +373,20 @@ function installOwnProperties(window, options) {
373373
return window._top;
374374
},
375375
get document() {
376-
return window._document;
376+
return idlUtils.wrapperForImpl(window._document);
377377
},
378378
get external() {
379379
return external;
380380
},
381381
get location() {
382-
return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location);
382+
return idlUtils.wrapperForImpl(window._document._location);
383383
},
384384
// [PutForwards=href]:
385385
set location(value) {
386386
Reflect.set(window.location, "href", value);
387387
},
388388
get history() {
389-
return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._history);
389+
return idlUtils.wrapperForImpl(window._document._history);
390390
},
391391
get navigator() {
392392
return navigator;
@@ -422,7 +422,7 @@ function installOwnProperties(window, options) {
422422
return window._origin;
423423
},
424424
get localStorage() {
425-
if (idlUtils.implForWrapper(window._document)._origin === "null") {
425+
if (window._document._origin === "null") {
426426
throw DOMException.create(window, [
427427
"localStorage is not available for opaque origins",
428428
"SecurityError"
@@ -432,7 +432,7 @@ function installOwnProperties(window, options) {
432432
return window._localStorage;
433433
},
434434
get sessionStorage() {
435-
if (idlUtils.implForWrapper(window._document)._origin === "null") {
435+
if (window._document._origin === "null") {
436436
throw DOMException.create(window, [
437437
"sessionStorage is not available for opaque origins",
438438
"SecurityError"
@@ -534,8 +534,8 @@ function installOwnProperties(window, options) {
534534
};
535535

536536
function timerInitializationSteps(handler, timeout, args, { methodContext, repeat, previousHandle }) {
537-
// This appears to be unspecced, but matches browser behavior for close()ed windows.
538-
if (!methodContext._document) {
537+
// Reject destroyed documents; this does not implement timer suspension while a document is not fully active.
538+
if (methodContext._document._isDestroyed) {
539539
return 0;
540540
}
541541

@@ -605,7 +605,7 @@ function installOwnProperties(window, options) {
605605
if (window._pretendToBeVisual) {
606606
window.requestAnimationFrame = function (callback) {
607607
callback = IDLFunction.convert(window, callback);
608-
if (!window._document) {
608+
if (window._document._isDestroyed) {
609609
return 0;
610610
}
611611

@@ -683,20 +683,19 @@ function installOwnProperties(window, options) {
683683
selected = webIDLConversions.boolean(selected);
684684

685685
const option = window._document.createElement("option");
686-
const impl = idlUtils.implForWrapper(option);
687686

688687
if (text !== "") {
689-
impl.text = text;
688+
option.text = text;
690689
}
691690
if (value !== undefined) {
692-
impl.setAttributeNS(null, "value", value);
691+
option.setAttributeNS(null, "value", value);
693692
}
694693
if (defaultSelected) {
695-
impl.setAttributeNS(null, "selected", "");
694+
option.setAttributeNS(null, "selected", "");
696695
}
697-
impl._selectedness = selected;
696+
option._selectedness = selected;
698697

699-
return option;
698+
return idlUtils.wrapperForImpl(option);
700699
}
701700
Object.defineProperty(Option, "prototype", {
702701
value: window.HTMLOptionElement.prototype,
@@ -713,16 +712,15 @@ function installOwnProperties(window, options) {
713712

714713
function Image(...args) {
715714
const img = window._document.createElement("img");
716-
const impl = idlUtils.implForWrapper(img);
717715

718716
if (args.length > 0) {
719-
impl.setAttributeNS(null, "width", String(args[0]));
717+
img.setAttributeNS(null, "width", String(args[0]));
720718
}
721719
if (args.length > 1) {
722-
impl.setAttributeNS(null, "height", String(args[1]));
720+
img.setAttributeNS(null, "height", String(args[1]));
723721
}
724722

725-
return img;
723+
return idlUtils.wrapperForImpl(img);
726724
}
727725
Object.defineProperty(Image, "prototype", {
728726
value: window.HTMLImageElement.prototype,
@@ -739,14 +737,13 @@ function installOwnProperties(window, options) {
739737

740738
function Audio(src) {
741739
const audio = window._document.createElement("audio");
742-
const impl = idlUtils.implForWrapper(audio);
743-
impl.setAttributeNS(null, "preload", "auto");
740+
audio.setAttributeNS(null, "preload", "auto");
744741

745742
if (src !== undefined) {
746-
impl.setAttributeNS(null, "src", String(src));
743+
audio.setAttributeNS(null, "src", String(src));
747744
}
748745

749-
return audio;
746+
return idlUtils.wrapperForImpl(audio);
750747
}
751748
Object.defineProperty(Audio, "prototype", {
752749
value: window.HTMLAudioElement.prototype,
@@ -783,7 +780,7 @@ function installOwnProperties(window, options) {
783780
}
784781
targetOrigin = whatwgURL.serializeURLOrigin(parsedURL);
785782

786-
if (targetOrigin !== idlUtils.implForWrapper(window._document)._origin) {
783+
if (targetOrigin !== window._document._origin) {
787784
// Not implemented.
788785
return;
789786
}
@@ -793,9 +790,9 @@ function installOwnProperties(window, options) {
793790
// TODO: event.origin - requires reference to incumbent window
794791
// TODO: event.ports
795792
// TODO: event.data - requires structured cloning
796-
setTimeout(() => {
793+
window._document._queueATask(() => {
797794
fireAnEvent("message", window, MessageEvent, { data: message });
798-
}, 0);
795+
});
799796
};
800797

801798
window.atob = function (str) {
@@ -823,16 +820,27 @@ function installOwnProperties(window, options) {
823820
};
824821

825822
window.stop = function () {
826-
const manager = idlUtils.implForWrapper(window._document)._requestManager;
823+
const manager = window._document._requestManager;
827824
if (manager) {
828825
manager.close();
829826
}
830827
};
831828

832829
window.close = function () {
833-
// Recursively close child frame windows, then ourselves (depth-first).
834-
for (let i = 0; i < window.length; ++i) {
835-
window[i].close?.();
830+
const doc = window._document;
831+
if (doc._isDestroyed) {
832+
return;
833+
}
834+
// Mark destruction before aborting descendants: interceptor abort listeners can reenter `window.close()`.
835+
doc._isDestroyed = true;
836+
837+
// Include child navigables in shadow trees, which are absent from our indexed Window properties.
838+
for (const child of doc._childDocuments) {
839+
child._defaultView.close();
840+
}
841+
if (doc._parentDocument !== null) {
842+
doc._parentDocument._childDocuments.delete(doc);
843+
doc._parentDocument = null;
836844
}
837845

838846
const { windowsInSameOrigin } = window._currentOriginData;
@@ -844,23 +852,8 @@ function installOwnProperties(window, options) {
844852
// Clear out all listeners. Any in-flight or upcoming events should not get delivered.
845853
idlUtils.implForWrapper(window)._removeAllEventListeners();
846854

847-
if (window._document) {
848-
if (window._document.body) {
849-
window._document.body.innerHTML = "";
850-
}
851-
852-
if (window._document.close) {
853-
// It's especially important to clear out the listeners here because document.close() causes a "load" event to
854-
// fire.
855-
idlUtils.implForWrapper(window._document)._removeAllEventListeners();
856-
window._document.close();
857-
}
858-
const doc = idlUtils.implForWrapper(window._document);
859-
if (doc._requestManager) {
860-
doc._requestManager.close();
861-
}
862-
delete window._document;
863-
}
855+
doc._removeAllEventListeners();
856+
doc._requestManager.close();
864857

865858
stopAllTimers();
866859
WebSocketImpl.cleanUpWindow(window);
@@ -887,7 +880,7 @@ function installOwnProperties(window, options) {
887880
};
888881

889882
window.getSelection = function () {
890-
return window._document.getSelection();
883+
return idlUtils.wrapperForImpl(window._document.getSelection());
891884
};
892885

893886
// The captureEvents() and releaseEvents() methods must do nothing

‎lib/jsdom/browser/resources/per-document-resource-loader.js‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@ module.exports = class PerDocumentResourceLoader {
1717
}
1818

1919
fetch(url, { element, onLoad, onError }) {
20-
if (!this._loadSubresources) {
20+
if (!this._loadSubresources || this._document._isDestroyed) {
2121
return null;
2222
}
2323

2424
const abortController = new AbortController();
25+
// Suppress frame completion when its child document is destroyed, even if the containing document survives.
26+
const resourceDocument = element._contentDocument ?? this._document;
2527

2628
// Add it to the request manager. The request manager is very old code, but it works with the contract of "has an
2729
// `abort()` method". One day this whole subsystem will be refactored to use `AbortController`s natively, but for
@@ -42,7 +44,7 @@ module.exports = class PerDocumentResourceLoader {
4244
this._requestManager.remove(abortController);
4345

4446
// If the request was aborted, don't fire error events
45-
if (cause && cause.name === "AbortError") {
47+
if (resourceDocument._isDestroyed || (cause && cause.name === "AbortError")) {
4648
return Promise.resolve();
4749
}
4850

@@ -63,6 +65,9 @@ module.exports = class PerDocumentResourceLoader {
6365

6466
const onLoadWrapped = response => {
6567
this._requestManager.remove(abortController);
68+
if (resourceDocument._isDestroyed) {
69+
return Promise.resolve();
70+
}
6671

6772
// Extract data and create a response-like object for compatibility
6873
const { body: data, status, headers, url: responseURL } = response;
@@ -82,7 +87,12 @@ module.exports = class PerDocumentResourceLoader {
8287

8388
return Promise.resolve(result)
8489
.then(() => {
85-
fireAnEvent("load", element);
90+
// A script's `load` completes its already-running execution algorithm, without another activity check
91+
// after evaluation or its cleanup microtasks. Frame completion still depends on its document's lifetime.
92+
// https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-element
93+
if (element.localName === "script" || !resourceDocument._isDestroyed) {
94+
fireAnEvent("load", element);
95+
}
8696

8797
return Promise.resolve();
8898
})

0 commit comments

Comments
 (0)