如何在不加载页面的情况下为空白选项卡设置 URL?
How can I set a URL for a blank tab without loading the page?
我正在开发一个 Firefox 扩展,它使用在线源代码查看器工具作为代理来下载被阻止的网页,然后将页面的 HTML 代码注入空白选项卡。
到目前为止,它按预期工作,但问题是新选项卡没有与之关联的 URL,因此为链接、图像、样式表和其他资源设置的所有相对路径都无效不再指向真实路径。
我试过 history.pushState()
和 history.replaceState()
,但只有当新的 URL 与当前的 URL 同源时它们才有效,而新标签根本没有 URL。
您可以使用 <base>
元素,
specifies the base URL to use for all relative URLs contained within a document.
您可以使用 var base = document.createElement('base');
创建它,然后在将其附加到文档的 <head>
之后,您可以使用其 href
属性指定文档的 baseURI:base.href= yourDocURI;
var anchor = document.createElement('a');
// set a relative path to it
anchor.href = '../../someDoc.html';
// create a new document
var doc = document.implementation.createHTMLDocument('empty page');
// append our anchor to the about:blank doc
doc.body.appendChild(anchor);
snippet.log('without base : '+ anchor.href);
var base = document.createElement('base');
base.href = "http://example.com/some/folder/index.html";
doc.head.appendChild(base);
snippet.log('with base : '+ anchor.href);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
我正在开发一个 Firefox 扩展,它使用在线源代码查看器工具作为代理来下载被阻止的网页,然后将页面的 HTML 代码注入空白选项卡。
到目前为止,它按预期工作,但问题是新选项卡没有与之关联的 URL,因此为链接、图像、样式表和其他资源设置的所有相对路径都无效不再指向真实路径。
我试过 history.pushState()
和 history.replaceState()
,但只有当新的 URL 与当前的 URL 同源时它们才有效,而新标签根本没有 URL。
您可以使用 <base>
元素,
specifies the base URL to use for all relative URLs contained within a document.
您可以使用 var base = document.createElement('base');
创建它,然后在将其附加到文档的 <head>
之后,您可以使用其 href
属性指定文档的 baseURI:base.href= yourDocURI;
var anchor = document.createElement('a');
// set a relative path to it
anchor.href = '../../someDoc.html';
// create a new document
var doc = document.implementation.createHTMLDocument('empty page');
// append our anchor to the about:blank doc
doc.body.appendChild(anchor);
snippet.log('without base : '+ anchor.href);
var base = document.createElement('base');
base.href = "http://example.com/some/folder/index.html";
doc.head.appendChild(base);
snippet.log('with base : '+ anchor.href);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>