// html data loaded from [http://example.org/some/path]
let htmlSource = `<!DOCTYPE html><html><head></head><body>
... <a href = "relative"></a> ...
</body></html>`;
const dom = new DOMParser().parseFromString(htmlSource, 'text/html');
// this returns the value of the attribute as is
dom.links[0].getAttribute('href'); // -> "relative" / nothing new here
// this should resolve urls
dom.links[0].href // -> wait, relative to WHAT??
// if you run this code while being on [http://google.com] you'll get
dom.links[0].href // -> "https://www.google.com/relative"
// Also,
dom.location // -> null / you can't change it
dom.baseURI // -> "https://www.google.com/" / read-only
Таким образом, похоже, что DOMParser неявно заставляет использовать текущую страницу location как baseURI для новых HTMLDocument.
Почему бы не дать разработчику возможность (третий аргумент?) явно указать местоположение документа?
Есть ли способ заставить DOMParser учитывать необязательный базовый URL? Обходные пути?





Вы должны использовать тег base внутри html-кода, вы даже можете добавить его динамически. Вот ваш пример:
const htmlSource = `
<!DOCTYPE html>
<html>
<head>
<base href = "https://www.example.com/">
</head>
<body>
<a href = "relative"></a>
</body>
</html>`;
const dom = new DOMParser().parseFromString(htmlSource, 'text/html');
console.info('DOM link ->', dom.links[0].href);Выведет:
DOM link -> https://www.example.com/relative
Добавьте его динамически:
let baseEl = dom.createElement('base');
baseEl.setAttribute('href', 'https://www.example.com');
dom.head.append(baseEl);
Хороший. Я бы добавил проверку наличия базового элемента
if (dom.head.getElementsByTagName('base').length == 0)