url - DOMParser 中的可选 baseURI(位置)?

标签 url dom uri relative-path domparser

// 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 作为新 HTMLDocumentbaseURI .

为什么不给开发者一个选项(第三个参数?)来明确指定文档位置?

有没有办法让 DOMParser 尊重可选的基本 url?解决方法?

最佳答案

您必须在 html 代码中使用 base 标签,您甚至可以动态添加它。这是您的示例:

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.log('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);

关于url - DOMParser 中的可选 baseURI(位置)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55232202/

相关文章:

php函数清除通过url传递的用户名和密码

javascript - 通过 settimer-function 将 textarea.value 存储到 MySQL 数据库而不丢失换行符

oauth-2.0 - Discord OAuth2 重定向 URI 操作方法

javascript - iMacros URL 提取问题 - 需要 Java Script EVAL 解决方案

javascript - 升级后 Tinymce 停止工作(修改 url)

javascript - 如何处理 javascript 中输入元素状态的编程更改

c# - 有没有一种简单的方法可以从 Windows Phone 中的 URI 获取查询字符串参数?

java - 在 Java 中编码 URL 的最佳方式

php - 不同浏览器中 $_GET 参数的变音问题 (PHP)

javascript - 带有 CSS 动画的动态 src 路径