[英]Open a new tab with custom HTML instead of a URL
我正在制作一个 Greasemonkey 脚本,并想打开一个新选项卡,该选项卡不会显示 URL,但会显示一些作为脚本一部分的 HTML。 所以基本上我想做这样的事情(这显然是行不通的):
window.open('<html><head></head><body></body></html>');
or
GM_openInTab('<html><head></head><body></body></html>');
欢迎任何提示!
你可以这样做:
var newWindow = window.open();
然后做
newWindow.document.write("ohai");
2021 年 4 月编辑:这个答案现在已经过时了。 Chrome 禁止将数据 URI 加载到顶部窗口中,并且iframe 解决方案在 Firefox 中对我不起作用。
原始答案:如果其他答案给您Error: Permission denied to access property "document"
,请参阅this question about how to handle same-origin policy questions ,或this one 。
或者,又快又脏,使用数据 URI:
var html = '<html><head></head><body>ohai</body></html>';
var uri = "data:text/html," + encodeURIComponent(html);
var newWindow = window.open(uri);
我把它放在这里以防万一有人需要它。 我已经找到了解决这个问题的方法,我创建了一个小网站( 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";
<a id="url">Click here to display following HTML in a link (see js):</a>
假设您有一个本地存储的.html
文件。 你可以做的是:
var newWindow = window.open();
newWindow.document.location.href = "/path/to/html/file";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.