javascript - 如何在不加载页面的情况下为空白选项卡设置 URL?

标签 javascript firefox-addon

我正在开发一个 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/

相关文章:

javascript - 有没有更易读的方式来表达 javascript 闭包?

javascript - 在应用新变换之前停止所有变换

javascript - Iframe 中的表单按钮,单击时在父窗口中加载

javascript - 接受除 5 个连续零以外的所有数字 : Javascript

javascript - 如何使用javascript打开firefox插件?

javascript - 为什么在 Firefox Addon 中导入的对象无法访问导入器导入的模块?

javascript - 使用 jQuery Slice 从下拉菜单中显示前 N 个项目

javascript - 如何在 Firefox 附加组件中获取右键单击选项卡的 URL

javascript - 当写入文件代码被注释时,附加生成器中的构建失败

javascript - 执行带有 Mozilla 扩展名的 .jar 文件