【问题标题】:Open a new tab with custom HTML instead of a URL使用自定义 HTML 而不是 URL 打开一个新选项卡
【发布时间】:2012-05-13 16:38:46
【问题描述】:

我正在制作一个 Greasemonkey 脚本,并想打开一个新选项卡,该选项卡不会显示 URL,但会显示一些作为脚本一部分的 HTML。所以基本上我想做这样的事情(这显然是行不通的):

window.open('<html><head></head><body></body></html>');
or
GM_openInTab('<html><head></head><body></body></html>');

欢迎任何提示!

【问题讨论】:

  • 我认为应该可以做 window.open('nonexistingURL')。将打开一个新选项卡,其中包含浏览器默认的“找不到页面”。应该可以在不存在的 url 上运行 GM 脚本。我试试看……

标签: javascript jquery greasemonkey


【解决方案1】:

你可以这样做:

var newWindow = window.open();

然后做

newWindow.document.write("ohai");

【讨论】:

  • 对我不起作用,新标签已打开,但它是空的,地址行中的 about:blank :-(.
  • 我认为这会转化为在底层(不安全)浏览器窗口上调用window.open,因此您正在查看的页面上的脚本可以访问新打开的窗口。 (这就是为什么有一个 GM_openInTab 函数毕竟来防止这种情况发生)。
  • 不,忘记我上面说的。这实际上是 GreaseMonkey 中的一个已知错误:GM 脚本将任何访问空窗口的尝试视为同源安全策略违规(他们不应该这样做)。
  • 另外,newWindow.document.body.innerHTML = 'ohai'; 也可以。
  • Chrome 将其视为弹出窗口,请确保允许(参见地址栏右侧的图标)。
【解决方案2】:

2021 年 4 月编辑:此答案现已过时。 Chrome banned 将数据 URI 加载到顶部窗口中,而 iframe solution 在 Firefox 中对我不起作用。

原答案:如果其他答案为您提供Error: Permission denied to access property "document",请参阅this question 了解如何处理同源策略问题,或this one

或者,又快又脏,使用数据 URI:

var html = '<html><head></head><body>ohai</body></html>';
var uri = "data:text/html," + encodeURIComponent(html);
var newWindow = window.open(uri);

【讨论】:

  • 很少需要,并且在大多数情况下,有更好的方法来解决“访问属性文档的权限被拒绝”错误:stackoverflow.com/questions/7995223stackoverflow.com/questions/22481340 等。
  • 我将您的正确建议编辑到我的答案中,因为最佳答案对某些人造成了这种情况,而且评论太多了。
  • 数据URI的长度有限制吗?
  • 当我使用您的答案时出现以下错误:“不允许将顶部框架导航到数据 URL”
  • 感谢@JCollier,我做了一些研究并将答案标记为已过时。
【解决方案3】:

我把它放在这里以防万一有人需要它。我已经找到了解决这个问题的方法,我创建了一个小网站 (https://tampermonkeykostyl.dacoconutnut.repl.co),您可以在哈希中提供 html!示例:(您可能需要中键单击 URL 才能在新选项卡中实际打开)

// get url
var el = document.getElementById("url");

// make html
var HTML = `
<h1>hi</h1>
if you can see this then cool <br>
<i>this should be italic</i> and <b>this should be bold</b>
`;

// insert html after the link to demonstrate
document.body.insertAdjacentHTML("beforeend", HTML); // https://stackoverflow.com/a/51432177/14227520

// set url href
el.href = "https://tampermonkeykostyl.dacoconutnut.repl.co/#" + encodeURI(HTML);

// make it open in new tab
el.target = "_blank";
&lt;a id="url"&gt;Click here to display following HTML in a link (see js):&lt;/a&gt;

【讨论】:

    【解决方案4】:

    假设您在本地存储了一个.html 文件。你可以这样做:

    var newWindow = window.open();
    newWindow.document.location.href = "/path/to/html/file";
    

    【讨论】:

    • 不,他们不能,因为 (a) 他们没有本地存储的 HTML 文件,并且 (b) 如果他们有,那将是一个相对于 GreaseMonkey 运行站点的 URL。
    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 2012-01-28
    • 2011-06-21
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多