使用自定义 URL 创建一个新的文档对象

Create a new Document object with custom URL

我正在尝试创建一个 URL 的文档对象,并将其设置为特定的自定义值。
我探索了下面提到的一些选项,但到目前为止无法做到。

我尝试过的一个示例方法,解释了哪里出了问题以及我想要什么:

//run context is the browser on page http://localhost

// example URL value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
const loadDocument = async (url: URL) => {
    // Fetching HTML from URL and parsing it into a document
    const docText = (await fetch(url)).text()
    const doc = new DOMParser().parseFromString(await fetchText(url.href), 'text/html')

    // the following will now be http://localhost, but I need it to be the URL the page is downloaded from 
    // i.e https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
    console.log(doc.URL) 
    
    // the consequence of it being wrong is that any links to external resources using relative paths
    // would be wrong as-well
    
    console.log(doc.querySelector('link[rel="stylesheet"]').href)
    // will be "http://localhost/static/css/main.1baf2b3e.chunk.css"
    // instead of "https://developer.mozilla.org/static/css/main.1baf2b3e.chunk.css"
}

我在这里试图完成的主要事情是使用相对链接在资源上获得正确的 URLs。我可以尝试通过遍历 DOM 并更改任何使用原始 URL 相对链接的内容的 URL 来手动修复此问题,但这似乎容易出错。因此 - 希望通过在文档上设置正确的基础 URL 而不是

来解决根中的问题

我尝试做的另一件事是 document.implementation.createHTMLDocument(),它会生成一个文档 about:blank 作为 URL,并且无法显式设置它 =\


尝试对 URL 属性 进行赋值似乎也没有做任何事情(并且在文档中明确标记为只读)

当您查询这些 href 属性时,您实际上是在将它们的值作为相对路径,根据它们 运行 的上下文评估为不同的绝对 urls。由于遍历整个 dom 并更改它会很疯狂,我可能会建议有机会注入一个基本 html 元素,该元素将暗示基本路径任何相对 url 将被映射到.它可以快速解决您的具体问题。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

The <base> HTML element specifies the base URL to use for all relative URLs in a document. There can be only one <base> element in a document.

条件必须是所有这些相关 url 都映射到相同的基础 url 当然,但如果您从工作着陆页抓取页面,这是理所当然的 url.请注意,CORS 策略有一些约束,特别是如果这些页面上的 js 需要对 domain 执行 ajax 查询。我的意思是这样的解决方案不会给你任何可能情况的钥匙。

<base href="https://thereal.com/absolute/url">

关于 baseURI 属性 的另一篇有趣的读物来自 MDN:

The read-only baseURI property of the Node interface returns the absolute base URL of the document containing the node.

The base URL is used to resolve relative URLs when the browser needs to obtain an absolute URL, for example when processing the HTML element's src attribute or the xlink:href or href attributes in SVG.

Although this property is read-only, its value is determined by an algorithm each time the property is accessed, and may change if the conditions changed.

The base URL is determined as follows:

  • By default, the base URL is the location of the document (as determined by window.location).
  • If it is an HTML Document and there is a <base> element in the document, the hrefvalue of the first Base element with such an
    attribute is used instead.