簡體   English   中英

使用自定義 HTML 而不是 URL 打開一個新選項卡

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM