JS打开新窗口(window.open() 、href)
·
JS打开新窗口
常用于文件、图片预览,或者加载一个新页面。
window.open() - 打开新窗口
用法:
window.open(strUrl, strWindowName, [strWindowFeatures]);
- strUrl: 新窗口需要载入的url地址,项目中我们打开的是一个在线文档。
- strWindowName:新窗口的名字,通过这个名字我们可以获得新窗口的引用,容易重复,如果我们希望每次打开新窗口都是一个全新的窗口,可以设置成关键字 “_blank”。
- strWindowFeatures:新窗口的一些设置,比如是否显示菜单栏,是否可以滚动和缩放窗口大小等。
示例:
window.open("https://www.baidu.com", "_blank", "resizable,scrollbars,status");
window.location - 更新当前窗口
加载给定URL的内容资源到这个Location对象所关联的对象上。
属性:
window.location.href = strUrl; //
方法:
window.location.assign(strUrl);
window.location.replace(strUrl); // 不会保存到浏览器会话的历史 History
a 标签 href 属性
<a href="strUrl" target="_blank">点击打开新窗口预览</a>
动态 a 标签
<div onclick="openNewWindow()">点击打开新窗口预览</div>
function openNewWindow() {
const strUrl = "https://www.baidu.com";
let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.target = "_blank";
a.href = strUrl;
a.click();
document.body.removeChild(a);
}
iOS window.open 无效
可以采用 window.location 和 a 标签 的方式解决。
或者调整脚本时序,先创建一个空窗口,再加载内容,而不是 window.open(strUrl) 同时完成。
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
安全问题
打开新窗口,可以通过 window.opener 获取原窗口的引用,利用这个引用,可以修改原窗口的属性,比如 url,所以解决安全问题就需要把这个引用切断。
window.open 的方式,如下处理
const newWindow = window.open("https://www.baidu.com");
newWindow.opener = null;
a 标签 的方式需要添加 rel 属性:
<a href="strUrl" target="_blank" rel="noopener noreferrer">
点击打开新窗口预览
</a>
性能问题
除了安全隐患外,还有可能造成性能问题。通过target="_blank"打开的新窗口,跟原来的页面窗口共用一个进程。如果这个新页面执行了一大堆性能不好的 JavaScript 代码,占用了大量系统资源,那你原来的页面也会受到池鱼之殃。
.END
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)