Javascript 打开一个新的选项卡/窗口并写入内容?
我正在使用Firefox编写和测试Javascript代码。我想打开一个新的选项卡/窗口并向其中写入一些内容,我尝试了Javascript 打开一个新的选项卡/窗口并写入内容?,javascript,firefox,firefox-addon,xpcom,Javascript,Firefox,Firefox Addon,Xpcom,我正在使用Firefox编写和测试Javascript代码。我想打开一个新的选项卡/窗口并向其中写入一些内容,我尝试了 var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); printWindow
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('','',宽度=200,高度=100')
myWindow.document.write(“这是‘myWindow’”)
myWindow.focus()
然而,我总是得到这个错误
[异常…”操作不安全。代码:“18”nsresult:
“0x80530012(安全性错误)”
有什么办法可以克服这个异常吗?编辑:从2018年开始,这个解决方案。因此,您可以重新在新窗口中打开关于:blank的
,并向其中添加内容
不要“写入”窗口,只需将所需内容打开即可:
var data = "<p>This is 'myWindow'</p>";
myWindow = window.open("data:text/html," + encodeURIComponent(data),
"_blank", "width=200,height=100");
myWindow.focus();
var data=“这是‘我的窗口’”;
myWindow=window.open(“数据:text/html,”+encodeURIComponent(数据),
“空白”、“宽度=200,高度=100”);
myWindow.focus();
供参考:var winPrint=window.open(“”,’左=0,上=0,宽=800,高=600,工具栏=0,滚动条=0,状态=0’);
winPrint.document.write('打印报告
Hellow World’);
winPrint.document.close();
截至2018年,window.open(uri)在chrome中不起作用在chrome、Firefox(除某些例外)、IE和Edge(以及可能启动的其他浏览器)中阻止了数据URL的顶级导航。它们显然通常用于网络钓鱼攻击,主要的浏览器供应商认为这种危险超过了合法使用案例所提供的价值
这解释了Firefox将阻止
- 使用以下内容导航到新的顶级数据URL文档的网页:
窗口。打开(“数据:…”;
window.location=“数据:…”
- 单击
并查看
至于如何在新选项卡或窗口中实际打开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中,。这可能与此处无关,但需要注意。非常感谢代码工作正常,但我想知道如何将新数据附加到新打开的窗口中?使用?因此,我按照您告诉我的方式尝试此代码,但似乎新元素根本没有附加到文档中。您能修复此问题吗请告诉我?@user433531:给窗口一个加载的机会?这已经不起作用了,可能是Google Chrome中发生了一些变化。“异常:操作不安全”是Firefox默认控制台上的一个bug(),Firefox上的Firebug控制台和Chromium默认控制台不会发生这种情况,我在这里评论说URI通常不会被阻止-数据URL是。显然,它们通常用于钓鱼攻击。Chrome和Firefox都会阻止它-请参阅、和。未捕获的语法错误:无效或意外的标记这将打开地址你现在在一个新的标签页上。你可能是指窗口。打开(“about:blank”,“u blank”)
。此外,浏览器会自动切换到新标签页,调用。focus()
是没有意义的。明白了-谢谢你的信息!我会继续进行编辑(并将其应用到我自己的代码中)。也谢谢你修复我的格式。这是我第一个可行的解决方案。我正在谷歌Chrome上试用
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();
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