Skip to content

Commit ae8170b

Browse files
committed
Improve context detection in DOM
1 parent b15189f commit ae8170b

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

html-api-debugger/view.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,10 +399,23 @@ const store = createStore(NS, {
399399
/** @type {Element|null} */
400400
let contextElement = null;
401401
if (store.state.contextHTMLForUse) {
402-
const walker = doc.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT);
403-
while (walker.nextNode()) {
404-
// @ts-expect-error It's an Element!
405-
contextElement = walker.currentNode;
402+
// An HTML document will always make HTML > HEAD + BODY.
403+
// But that may not be the intended context.
404+
// Guess the intended context in case the HEAD and BODY elements are empty.
405+
if (doc.body.hasChildNodes() || doc.head.hasChildNodes()) {
406+
const walker = doc.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT);
407+
while (walker.nextNode()) {
408+
// @ts-expect-error It's an Element!
409+
contextElement = walker.currentNode;
410+
}
411+
} else {
412+
if (/<body\W/i.test(store.state.contextHTMLForUse)) {
413+
contextElement = doc.body;
414+
} else if (/<head\W/i.test(store.state.contextHTMLForUse)) {
415+
contextElement = doc.head;
416+
} else {
417+
contextElement = doc.documentElement;
418+
}
406419
}
407420
if (contextElement) {
408421
store.state.DOM.contextNode = contextElement.nodeName;

0 commit comments

Comments
 (0)