我正在制作一个 Greasemonkey 脚本,并想打开一个新选项卡,该选项卡不会显示 URL,但会显示一些作为脚本一部分的 HTML。所以基本上我想做这样的事情(这显然是行不通的):
window.open('<html><head></head><body></body></html>');
or
GM_openInTab('<html><head></head><body></body></html>');
欢迎任何提示!
我正在制作一个 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 the 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);
I am putting this here just in case anyone will need this. I have made a way to solve this problem, i created a little website (https://tampermonkeykostyl.dacoconutnut.repl.co) that you can give html to in the hash! Example: (you might need to middle click the url for it to actually open in new tab)
// 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";