我正在使用 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()
但是我总是得到这个错误
[Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)"
有什么办法可以解决这个异常吗?
最佳答案
数据 URL 的顶级导航已在 Chrome、Firefox(有一些异常(exception))、IE 和 Edge(以及其他可能启动的浏览器)中被阻止。它们显然常用于网络钓鱼攻击,主要浏览器 vendor 认为危险超过了合法用例所提供的值(value)。
这Mozilla security blog post解释 Firefox 将阻止
- Web page navigating to a new top-level data URL document using:
window.open("data:…");
window.location = "data:…"
- clicking
<a href="data:…">
(including ctrl+click, ‘open-link-in-*’, etc).- Web page redirecting to a new top-level data URL document using:
- 302 redirects to
"data:…"
- meta refresh to
"data:…"
- External applications (e.g., ThunderBird) opening a data URL in the browser
但不会阻塞
- User explicitly entering/pasting
"data:…"
into the address bar- Opening all plain text data files
- Opening
"data:image/*"
in top-level window, unless it’s"data:image/svg+xml"
- Opening
"data:application/pdf"
and"data:application/json"
- Downloading a data: URL, e.g. ‘save-link-as’ of
"data:…"
您还可以阅读 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 .这在这里可能无关紧要,但需要注意。
关于javascript - 打开一个新的选项卡/窗口并向其中写入内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11965087/