我正在使用Execute JS在Firefox中编写和测试Javascript代码。我想打开一个新的标签/窗口并写一些东西,我试过了
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
printWindow = win.open("about:blank");
printWindow = wm.getMostRecentWindow("navigator:browser");
printWindow.gBrowser.selectedBrowser.contentDocument.write('hello');
和
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("<p>This is 'myWindow'</p>")
myWindow.focus()
但是我总是得到这个错误
[例外......“手术不安全。”代码:“18”nsresult:“0x80530012(SecurityError)”
有没有办法解决这个异常?
编辑:截至2018年,这个解决方案no longer works。所以你回到在新窗口中打开about:blank
并向其中添加内容。
不要“写”到窗口,只需用你需要的内容打开它:
var data = "<p>This is 'myWindow'</p>";
myWindow = window.open("data:text/html," + encodeURIComponent(data),
"_blank", "width=200,height=100");
myWindow.focus();
供参考:data URIs
Chrome,Firefox(有一些例外情况),IE和Edge(以及其他可能的其他浏览器)都阻止了对数据网址的顶级导航。它们显然通常用于网络钓鱼攻击,主要浏览器供应商认为危险性超过了合法用例提供的价值。
这个Mozilla security blog post解释说Firefox会阻止
- 使用以下方法导航到新的顶级数据URL文档的网页:
window.open("data:…");
window.location = "data:…"
点击<a href="data:…">
(包括ctrl + click,'open-link-in- *'等)。- 网页使用以下方法重定向到新的顶级数据URL文档: 302重定向到
"data:…"
元刷新到"data:…"
- 外部应用程序(例如,ThunderBird)在浏览器中打开数据URL
但不会阻止
- 用户明确地将
"data:…"
输入/粘贴到地址栏中- 打开所有纯文本数据文件
- 在顶层窗口打开
"data:image/*"
,除非它是"data:image/svg+xml"
- 打开
"data:application/pdf"
和"data:application/json"
- 下载数据:URL,例如
"data:…"
的'save-link-as'
您还可以阅读proposal to deprecate and remove top-frame navigation to data URLs in Chrome并查看current Chrome status indicating that is has been removed。
至于如何在新的选项卡或窗口中实际打开HTML,这应该足够了:
var tab = window.open('about:blank', '_blank');
tab.document.write(html); // where 'html' is a variable containing your HTML
tab.document.close(); // to finish loading the page
请注意,至少在Chrome中,external scripts injected via document.write might not be loaded on slower connections。这可能与此无关,但值得注意。
var winPrint = window.open('', '', 'left=0,top=0,width=800,height=600,toolbar=0,scrollbars=0,status=0');
winPrint.document.write('<title>Print Report</title><br /><br />
Hellow World');
winPrint.document.close();
window.open(uri)在2018年的chrome中不起作用