使用 window 对象的 open() 方法可以打开一个新窗口。用法如下:

window.open(url, target, features)

该方法返回值为新创建的 window 对象,使用它可以引用新创建的窗口。

url
可选字符串,声明新窗口需要载入的 url 地址,可以是 web 上的 html 页面也可以是图片文件或者其他任何浏览器支持的文件格式。
如果省略,或者为空,则新窗口就不会显示任何文档。

target
可选字符串,声明新窗口的名称。该字符串可以用来作为超链接 <a> 或表单 <form> 元素的目标属性值。字符串中不能含有空白字符。
如果该参数指定了一个已经存在的窗口,那么 open() 方法就不再创建一个新窗口,而只是返回对指定窗口的引用,在这种情况下,features 参数将被忽略。

features
可选字符串,声明了将要打开的窗口的一些特性 (窗口功能和工具栏),具体说明如下表所示。
如果省略该参数,新窗口将具有所有标准特征。

Features参数

特征说明
width = pixels窗口的文档显示区的宽度,包括滚动条。单位为元素。最小值100。
height = pixels窗口文档显示区的高度,包括滚动条。单位为像素。最小值100。
left = pixels窗口的 x 坐标。单位为像素。
top = pixels窗口的 y 坐标。单位为像素。
popup打开弹窗。popup=yespopup=1popup=truepopup是一样的效果
noopener如果设置了此功能,新窗口将不能通过window访问原始窗口,返回null。
noreferrer如果设置了此功能,新窗口无法获取来源页面的window。
  • 如果没有启用popup,并且没有声明窗口特性,那么将打开一个选项卡。
  • noopener, noreferrer为打开第三方网址而设置,功能和链接的 rel="noopener noreferrer" 一样,避免新窗口访问源窗口的window对象而造成的信息泄露。
  • 原有的location、menubar、resizable、scrollbars、status、toolbar等tokenizedFeatures属性,现代浏览器已不再支持。

举例

在新窗口打开

window.open();  //打开一个空白页about:blank
window.open('//qq.com');  //打开一个新tab
window.open('//qq.com','','popup');  //打开一个弹窗
window.open('//qq.com','','left=100,top=100,width=800,height=600');  //打开一个弹窗,设置了位置和尺寸

打开一个tab并写入内容

var win = window.open();
win.document.write('<h1>这是新打开的窗口</h1>');
win.focus();  //让原窗口获取焦点

可以使用win.document.write();win.document.body.innerHTML = "HTML";写入HTML代码

打开一个弹窗,并改写内容

let newWindow = open('/', 'example', 'width=300,height=300')
newWindow.focus();
alert(newWindow.location.href); // (*)about:blank, loading hasn't started yet
newWindow.onload = function() {
  let html = `<div style="font-size:30px">Welcome!</div>`;
  newWindow.document.body.insertAdjacentHTML('afterbegin', html);
};

关闭弹窗

let newWindow = open('/', 'example', 'width=300,height=300');
newWindow.onload = function() {
  newWindow.close();
  alert(newWindow.closed); // true
};
本文最后更新时间:2023年3月12日

标签: js

添加新评论