我正在使用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" NS结果: "0x80530012(安全错误)"
有什么办法可以解决这个异常吗?
Chrome,Firefox(有一些例外),IE和Edge(以及可能的其他浏览器启动)中,数据URL的顶级导航已被阻止。它们显然通常用于网络钓鱼攻击,主要浏览器供应商认为危险超过了合法用例提供的价值。
这篇Mozilla安全博客文章解释了Firefox将阻止
使用
- 以下命令导航到新的顶级数据 URL 文档的网页:
使用
window.open("data:…");
window.location = "data:…"
- 单击
<a href="data:…">
(包括 ctrl+单击、"打开链接-in-*"等)。- 以下命令重定向到新的顶级数据 URL 文档的网页:
- 302重定向至
"data:…"
- 元刷新到
"data:…"
- 外部应用程序(例如 ThunderBird)在浏览器中打开数据 URL
但不会阻止
您还可以阅读有关弃用和移除指向 Chrome
- 用户在地址栏中显式输入/粘贴
"data:…"
- 打开所有纯文本数据文件
- 在顶级窗口中打开
"data:image/*"
,除非它是"data:image/svg+xml"
- 开幕
"data:application/pdf"
和"data:application/json"
- 下载数据:网址,例如
"data:…"
的"链接另存为"
中数据网址的顶部框架导航的提案,并查看当前 Chrome 状态(表明该状态已被移除)。
至于如何在新标签或窗口中实际打开 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 中,通过 document.write 注入的外部脚本可能不会在较慢的连接上加载。这可能在这里无关紧要,但需要注意。
编辑:截至2018年,此解决方案不再有效。因此,您将返回到在新窗口中打开about:blank
并向其中添加内容。
不要"写入"窗口,只需使用所需的内容打开它:
var data = "<p>This is 'myWindow'</p>";
myWindow = window.open("data:text/html," + encodeURIComponent(data),
"_blank", "width=200,height=100");
myWindow.focus();
供参考:数据 URI
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();
Windows.open(uri) 截至 2018 年在 Chrome 中不起作用