我正在开发一个 Firefox 扩展,它使用在线源代码查看器工具作为代理来下载被阻止的网页,然后将页面的 HTML 代码注入(inject)空白选项卡。
到目前为止,它按预期工作,但问题是新选项卡没有与之关联的 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>
关于javascript - 如何在不加载页面的情况下为空白选项卡设置 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669931/